---
title: "Node.js/JavaScript Modernization with Autohand Code"
description: "Upgrade legacy JavaScript applications to modern ES2022+. Transform callback-based code to async/await patterns and modern frameworks with Autohand Code."
sidebar:
  label: "Node.js Modernization"
seo:
  description: "Modernize Node.js and JavaScript applications with Autohand Code AI. Upgrade from legacy JavaScript to ES2022+, migrate frameworks, and modernize code architecture."
---

:::tip
**Modern JavaScript:** ES2022+ offers powerful features like top-level await, class fields, and improved async patterns. Autohand Code helps modernize legacy JavaScript codebases efficiently. [Get started](https://autohand.ai/contact-sales/).
:::

:::tip
**Related Skills:** Modernize your JavaScript codebase with specialized skills from [Skilled](https://skilled.autohand.ai). Explore [React and Node.js migration skills](https://skilled.autohand.ai/categories/frameworks), [JavaScript/TypeScript skills](https://skilled.autohand.ai/categories/languages), and [async/await modernization workflows](https://skilled.autohand.ai/categories/workflows).
:::

## Why modernize JavaScript/Node.js? [#overview]

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 [#assessment]

Assess your JavaScript application for modernization readiness:

```bash
# 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 [#syntax-upgrade]

Transform legacy JavaScript to modern ES2022+ syntax:

```bash
# 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

```js
// 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:

```js
// 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 [#nodejs-upgrade]

Upgrade Node.js applications to modern versions:

```bash
# 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

```js
// 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:

```js
// 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 [#framework-migration]

Migrate between JavaScript frameworks and patterns:

```bash
# 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

```js
// 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:

```js
// 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 [#typescript-migration]

Add TypeScript to existing JavaScript codebases:

```bash
# 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

```ts
// 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:

```ts
// 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 [#testing]

Ensure modernization doesn't break functionality:

```bash
# 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

```js
// 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 [#best-practices]

### 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 [#case-study]

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
