Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

Node.js/JavaScript Modernization with Autohand Code

Upgrade legacy JavaScript applications to modern ES2022+. Transform callback-based code to async/await patterns and modern frameworks with Autohand Code.

Why modernize JavaScript/Node.js?

Modern JavaScript and Node.js offer significant advantages:

  • Better performance with modern V8 optimizations
  • Cleaner code with async/await and modern syntax
  • Enhanced security with updated Node.js versions
  • Improved developer experience with modern tooling
  • Access to modern ecosystem and libraries

JavaScript/Node.js codebase assessment

Assess your JavaScript application for modernization readiness:

# Create an AGENTS.md to record your targets (ES2022, Node.js 20)
autohand init

# Generate a modernization roadmap in read-only plan mode
autohand -p "Assess this codebase for an upgrade to ES2022 and Node.js 20. Write a roadmap to docs/js-roadmap.md" --plan

# Assessment includes:
# - ES version compatibility
# - Node.js version compatibility
# - Package dependency analysis
# - Framework modernization opportunities

JavaScript syntax modernization

Transform legacy JavaScript to modern ES2022+ syntax:

# Preview the syntax upgrade as a patch
autohand -p "Convert callbacks in src/ to async/await and use ES2022 class fields" --patch --output js-syntax.patch
git apply --check js-syntax.patch

# Run the syntax upgrade in an isolated git worktree
autohand --worktree js-syntax -p "Convert callbacks in src/ to async/await and use ES2022 class fields. Run npm test after each file"

Example transformations

// Before (ES5)
function fetchData(callback) {
  setTimeout(function() {
    callback(null, { data: 'result' });
  }, 1000);
}

function processData(data, callback) {
  var processed = data.map(function(item) {
    return item.toUpperCase();
  });
  callback(null, processed);
}

// Usage
fetchData(function(err, result) {
  if (err) {
    console.error(err);
    return;
  }
  processData(result.data, function(err, processed) {
    if (err) {
      console.error(err);
      return;
    }
    console.log(processed);
  });
});

Becomes:

// After (ES2022)
class DataProcessor {
  #cache = new Map();
  
  async fetchData() {
    return new Promise(resolve => {
      setTimeout(() => resolve({ data: 'result' }), 1000);
    });
  }
  
  processData(data) {
    return data.map(item => item.toUpperCase());
  }
  
  async fetchAndProcess() {
    try {
      const result = await this.fetchData();
      return this.processData(result.data);
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

// Usage
const processor = new DataProcessor();
processor.fetchAndProcess()
  .then(processed => console.log(processed))
  .catch(error => console.error(error));

Node.js version upgrade

Upgrade Node.js applications to modern versions:

# Plan the upgrade from Node.js 12 to 20 (read-only)
autohand -p "Plan an upgrade from Node.js 12 to 20, including CommonJS to ES modules and worker_threads where useful" --plan

# Execute the upgrade in an isolated git worktree
autohand --worktree node-20 -p "Upgrade this project from Node.js 12 to 20 and migrate CommonJS to ES modules. Run npm test when done"

CommonJS to ES Modules migration

// Before (CommonJS)
const fs = require('fs');
const path = require('path');
const utils = require('./utils');

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

module.exports = { readFile };

Becomes:

// After (ES Modules)
import fs from 'fs/promises';
import path from 'path';
import { formatData } from './utils.js';

export async function readFile(filePath) {
  try {
    const data = await fs.readFile(filePath, 'utf8');
    return formatData(data);
  } catch (error) {
    throw new Error(`Failed to read file: ${error.message}`);
  }
}

Framework modernization

Migrate between JavaScript frameworks and patterns:

# Migrate Express to modern patterns
autohand --worktree express-modern -p "Modernize the Express app: async route handlers, Router modules, central error middleware"

# Migrate jQuery to vanilla JavaScript
autohand --worktree no-jquery -p "Replace jQuery usage in public/js with vanilla DOM APIs"

# Migrate to TypeScript
autohand --worktree typescript -p "Add TypeScript to this project and convert src/ from JavaScript"

Express.js modernization example

// Before (Express 3.x)
var express = require('express');
var app = express();

app.get('/api/users', function(req, res) {
  User.find({}, function(err, users) {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.json(users);
    }
  });
});

app.listen(3000);

Becomes:

// After (Express 4.x + modern patterns)
import express from 'express';
import { User } from './models/User.js';

const app = express();
const router = express.Router();

router.get('/users', async (req, res, next) => {
  try {
    const users = await User.find({});
    res.json(users);
  } catch (error) {
    next(error);
  }
});

app.use('/api', router);
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: err.message });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

TypeScript integration

Add TypeScript to existing JavaScript codebases:

# Preview what the TypeScript migration would change
autohand -p "Add a strict tsconfig.json with declaration output and convert src/ to TypeScript" --dry-run

# Run the migration file by file in a worktree, checkpointing as it goes
autohand --worktree typescript --auto-mode "Convert src/ to TypeScript with strict types and declaration output. Run npx tsc --noEmit after each file" --max-iterations 30 --checkpoint-interval 5

JavaScript to TypeScript example

// Before (JavaScript)
function calculateTotal(items, tax = 0.1) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0) * (1 + tax);
}

const result = calculateTotal([
  { price: 10, quantity: 2 },
  { price: 5, quantity: 3 }
]);

Becomes:

// After (TypeScript)
interface CartItem {
  price: number;
  quantity: number;
}

function calculateTotal(items: CartItem[], tax: number = 0.1): number {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0) * (1 + tax);
}

const result: number = calculateTotal([
  { price: 10, quantity: 2 },
  { price: 5, quantity: 3 }
]);

Testing and validation

Ensure modernization doesn’t break functionality:

# Generate characterization tests for the legacy code before changing it
autohand -p "Write Jest characterization tests for src/calculator.js that pin its current behaviour"

# Validate the modernized code against those tests
npm test

# Run the suite on each Node.js version you support (for example with nvm)
for v in 18 20 22; do nvm exec $v npm test; done

Modern test example

// Generated test (Jest)
import { calculateTotal } from './calculator.js';

describe('calculateTotal', () => {
  test('calculates total with default tax', () => {
    const items = [
      { price: 10, quantity: 2 },
      { price: 5, quantity: 3 }
    ];
    
    const result = calculateTotal(items);
    
    expect(result).toBe(38.5); // (20 + 15) * 1.1
  });
  
  test('calculates total with custom tax', () => {
    const items = [{ price: 100, quantity: 1 }];
    
    const result = calculateTotal(items, 0.2);
    
    expect(result).toBe(120); // 100 * 1.2
  });
});

Best practices for JavaScript/Node.js modernization

Pre-modernization preparation

  • Comprehensive testing: Achieve >90% test coverage before modernization
  • Dependency audit: Identify all npm packages and compatibility
  • Performance baseline: Document current performance metrics
  • Security assessment: Address known vulnerabilities in dependencies
  • Build process review: Evaluate current build and deployment pipeline

Modernization strategy

  • Incremental approach: Modernize module by module rather than all at once
  • Backward compatibility: Maintain compatibility during transition
  • Feature flags: Use feature toggles for gradual rollout
  • Parallel development: Support both old and new versions temporarily
  • API compatibility: Ensure external APIs remain functional

Code transformation

  • Callback to async/await: Convert callback patterns to async/await
  • Class syntax: Use modern class syntax and features
  • Destructuring: Apply array and object destructuring patterns
  • Arrow functions: Use arrow functions where appropriate
  • Template literals: Replace string concatenation with template literals

Node.js modernization

  • ES modules: Migrate from CommonJS to ES modules
  • Worker threads: Use worker threads for CPU-intensive tasks
  • Async hooks: Implement proper async resource management
  • Security updates: Keep Node.js version current for security
  • Performance monitoring: Add modern performance monitoring

Quality assurance

  • Type checking: Add TypeScript or JSDoc for type safety
  • Linting: Use ESLint with modern configurations
  • Code formatting: Implement Prettier for consistent formatting
  • Security scanning: Run npm audit and security scanners
  • Performance testing: Validate performance improvements

Common pitfalls to avoid

  • this context issues: Be careful with this in arrow functions
  • Promise rejection: Handle promise rejections properly
  • Module compatibility: Verify all modules support target Node.js version
  • Async/await errors: Use proper error handling with try/catch
  • Build tooling: Update build tools and configurations

Success story: SaaS platform

A B2B SaaS company modernized their Node.js application:

  • Scope: 200K lines of ES5 + Node.js 12 code
  • Target: ES2022 + Node.js 20 + TypeScript
  • Timeline: 6 months phased migration
  • Results: 40% performance improvement, enhanced maintainability
  • Benefits: Better debugging, type safety, and developer experience

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification