# Module System (CJS vs ESM)

> What is the difference between CommonJS and ES Modules in Node.js? How does Node decide which one a file uses, and when would you use each?

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-module-system
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is the difference between CommonJS and ES Modules in Node.js? How does Node decide which one a file uses, and when would you use each?

## Answer

CommonJS (CJS) is Node's original module system, using `require()` and `module.exports`, and it loads modules synchronously at runtime. ES Modules (ESM) are the JavaScript standard, using `import` and `export`, and they are parsed statically before any code runs, which enables top-level `await`, tree-shaking, and the same syntax as the browser. New projects should default to ESM; CJS remains everywhere in older code and packages.

### Key differences

| Aspect | CommonJS | ES Modules |
| --- | --- | --- |
| Syntax | `require`, `module.exports` | `import`, `export` |
| Loading | Synchronous, at runtime | Parsed first, then linked and evaluated |
| Exports | A copy of the value at require time | Live bindings to the exporter's variables |
| Conditional loading | `require()` anywhere | Static `import` at top; `import()` for dynamic |
| Top-level await | No | Yes |
| `__dirname`, `__filename` | Available | Use `import.meta.dirname` / `import.meta.filename` (Node 20.11+) |
| File extensions in imports | Optional | Required for relative paths (`./utils.js`) |
| `this` at top level | `module.exports` | `undefined` |

### How Node decides a file's module type

1. `.mjs` is always ESM and `.cjs` is always CommonJS.
2. For `.js`, Node looks at the nearest `package.json`: `"type": "module"` means ESM, `"type": "commonjs"` or no field means CJS.
3. If there is no `type` field and the file contains ESM syntax such as `import`, Node 22.7+ detects that and loads it as ESM (syntax detection), but setting `type` explicitly is faster and clearer.

### Interop between the two

- **ESM importing CJS** works: `import pkg from 'cjs-lib'` gives you `module.exports` as the default export, and Node tries to detect named exports.
- **CJS requiring ESM** used to require `await import()`. Since Node 22.12 and 20.19, `require()` can load ES modules synchronously as long as they do not use top-level `await`. This removed much of the migration pain for library authors.
- Libraries that need to support both use the `exports` field in `package.json` with `import` and `require` conditions. Watch out for the **dual package hazard**: if both copies get loaded, you get two instances of the module's state.

### Gotchas you will hit

- Forgetting the `.js` extension in an ESM relative import gives `ERR_MODULE_NOT_FOUND`.
- In TypeScript with `"module": "nodenext"`, you write `import './utils.js'` even though the source file is `utils.ts`.
- JSON imports in ESM need an import attribute: `import data from './data.json' with { type: 'json' }`.
- Both systems cache modules, so a module's top-level code runs once per process. Circular dependencies behave differently: CJS hands you a partially filled `exports` object, while ESM throws a `ReferenceError` if you touch a binding before it is initialized.

### What to use

Use ESM for new apps and libraries, set `"type": "module"`, and rely on `require(esm)` only when bridging old code. Keep CJS for existing codebases where a migration has no clear payoff, and for tools or plugins that still expect it.

## Code examples

### CommonJS in practice

```
// math.cjs
let calls = 0;
function add(a, b) { calls++; return a + b; }
module.exports = { add, getCalls: () => calls, calls };

// app.cjs
const math = require('./math.cjs');
console.log(math.add(2, 3));      // 5
console.log(math.calls);          // 0  (copied value, not live)
console.log(math.getCalls());     // 1

// Conditional, lazy require (CJS only)
if (process.env.NODE_ENV !== 'production') {
  const debug = require('./debug-tools.cjs');
  debug.enable();
}

// Same object every time: modules are cached
console.log(require('./math.cjs') === math); // true
```

require() is synchronous and can be called conditionally. Exports are copied at require time, and the module is cached after the first load, so it behaves like a singleton.

### ES Modules in practice

```
// math.js  (package.json has "type": "module")
export let calls = 0;
export function add(a, b) { calls++; return a + b; }
export default function multiply(a, b) { return a * b; }

// app.js
import multiply, { add, calls } from './math.js'; // extension required
import { readFile } from 'node:fs/promises';
import config from './config.json' with { type: 'json' };

console.log(add(2, 3), calls); // 5 1  (live binding)
console.log(multiply(4, 5));   // 20

// Top-level await
const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
console.log(pkg.name, config.env);

// Replacements for __dirname / __filename (Node 20.11+)
console.log(import.meta.dirname, import.meta.filename);

// Dynamic import works in both CJS and ESM
const { default: chalk } = await import('chalk');
```

ESM exports are live bindings, top-level await works, and import.meta replaces \__dirname. Relative imports must include the file extension.

### package.json for a dual CJS and ESM library

```
{
  "name": "@acme/money",
  "version": "2.0.0",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  },
  "engines": { "node": ">=20.19" }
}
```

The exports field picks the right entry point based on how the package is loaded. types should come first so TypeScript resolves declarations correctly.

## Key points

- CJS: require/module.exports, synchronous, values copied at require time.
- ESM: import/export, statically analysed, live bindings, top-level await.
- .mjs is always ESM, .cjs always CJS, .js follows the nearest package.json "type".
- Since Node 22.12 and 20.19, require() can load ESM that has no top-level await.
- In ESM use import.meta.dirname and import.meta.filename instead of \__dirname and \__filename.

## Common follow-up questions

- How do circular dependencies behave in CommonJS vs ES Modules?
- Why does tree-shaking work well with ESM but poorly with CommonJS?
- What is the dual package hazard and how do you avoid it?
- How does the exports field in package.json affect deep imports?

## Interview tips

- Go beyond syntax: mention static analysis, live bindings, and top-level await.
- Mentioning require(esm) landing in Node 22.12 shows you track the ecosystem.
- Share a concrete migration pain you have hit, such as missing file extensions or \__dirname in ESM.

## Concepts covered

CommonJS, ES Modules, require(esm), package.json type, exports field, Tree-shaking

Previous: [Node.js Basics & Runtime](https://www.internhack.in/learn/interview/nodejs-interview/node-basics-runtime) · Next: [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [Path & OS Modules](https://www.internhack.in/learn/interview/nodejs-interview/node-path-os)
- [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server)
- [Express.js Fundamentals](https://www.internhack.in/learn/interview/nodejs-interview/node-express-fundamentals)
- [Routing & Route Parameters](https://www.internhack.in/learn/interview/nodejs-interview/node-routing-params)
- [Middleware Deep Dive](https://www.internhack.in/learn/interview/nodejs-interview/node-middleware-deep-dive)
- [Request Validation (Zod/Joi)](https://www.internhack.in/learn/interview/nodejs-interview/node-request-validation)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
