Module System (CJS vs ESM)

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

AspectCommonJSES Modules
Syntaxrequire, module.exportsimport, export
LoadingSynchronous, at runtimeParsed first, then linked and evaluated
ExportsA copy of the value at require timeLive bindings to the exporter's variables
Conditional loadingrequire() anywhereStatic import at top; import() for dynamic
Top-level awaitNoYes
__dirname, __filenameAvailableUse import.meta.dirname / import.meta.filename (Node 20.11+)
File extensions in importsOptionalRequired for relative paths (./utils.js)
this at top levelmodule.exportsundefined

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

Gotchas you will hit

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

Common follow-up questions

Interview tips

Concepts covered

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

More Node.js Interview questions