Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Concepts and Pitfalls

ESM versus CommonJS in Node.js

Compare ES modules and CommonJS in Node.js: syntax, loading, top-level await, __dirname, JSON, interop with require() and import(), and tips for migrating.

Node.js has two module systems. CommonJS (CJS) is the original: require() and module.exports, loaded synchronously. ES modules (ESM) are the language standard: import and export, loaded asynchronously, with static structure that tools can analyze. New code should use ESM; CommonJS remains fully supported and is what millions of existing packages use.

Which system a file uses is decided by its extension and the nearest package.json: .mjs is always ESM, .cjs is always CommonJS, and .js follows the "type" field ("module" or "commonjs", the default).

NODE
import { readFile } from 'node:fs/promises';   // ESM
// const { readFile } = require('node:fs/promises');   // CommonJS

Try it

Node.js What an ES module has and lacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js The same checks in CommonJS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Side-by-side comparison

CommonJS ES modules
Syntax require(), module.exports import, export
Loading Synchronous, at the point of the call Asynchronous; imports are resolved before code runs
Structure Dynamic: require(name) can be anywhere Static import at top level; import() for dynamic loads
Top-level await Not allowed Allowed
Strict mode Opt in with 'use strict' Always strict
this at top level module.exports undefined
__filename, __dirname Provided Use import.meta.filename and import.meta.dirname (Node 20.11+)
JSON require('./data.json') import data from './data.json' with { type: 'json' }
File extensions in paths Optional (./util finds util.js) Required in relative specifiers (./util.js)
Directory imports ./dir finds index.js Not supported; write ./dir/index.js
Bindings Copies of values at require time Live bindings to the exporter's variables
Cache require.cache, can be cleared One immutable module map per realm

Interoperability

  • ESM can import CommonJS. import pkg from './legacy.cjs' gives the whole module.exports as the default export. Named imports work only when Node can detect the names statically, so prefer the default import when in doubt.
  • CommonJS can import() ESM, always, returning a promise.
  • require() of an ES module is supported in current Node releases when the module graph has no top-level await; otherwise it throws ERR_REQUIRE_ASYNC_MODULE. See require(esm).
  • createRequire(import.meta.url) gives an ES module a working require() for loading CommonJS-only or .node addons.

Migration tips

  • Pick the system per package with "type": "module" in package.json; use .cjs and .mjs for exceptions.
  • Add node: prefixes and file extensions to relative imports first; they work in both systems.
  • Replace __dirname with import.meta.dirname and require.main === module with a check of import.meta.filename against process.argv[1].
  • Replace conditional require() with top-level await import().
  • Publish dual packages with the exports field's conditions; see Conditional exports.

Usage notes

  • A mistaken extension shows up as syntax errors. Cannot use import statement outside a module means a CommonJS file used import; require is not defined in ES module scope means the reverse.
  • Live bindings mean an exported let changed by the exporter is seen updated by importers, which module.exports copies do not do.
  • Circular imports work in both but differ: CJS may see a half-filled exports; ESM may see a variable in its temporal dead zone.
  • Performance is similar. Choose by ecosystem and tooling needs, not speed.
  • Tools differ. Test runners, loaders and bundlers need ESM support; most current ones have it.