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).
import { readFile } from 'node:fs/promises'; // ESM // const { readFile } = require('node:fs/promises'); // CommonJS
Try it
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.
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 wholemodule.exportsas 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-levelawait; otherwise it throwsERR_REQUIRE_ASYNC_MODULE. See require(esm).createRequire(import.meta.url)gives an ES module a workingrequire()for loading CommonJS-only or.nodeaddons.
Migration tips
- Pick the system per package with
"type": "module"inpackage.json; use.cjsand.mjsfor exceptions. - Add
node:prefixes and file extensions to relative imports first; they work in both systems. - Replace
__dirnamewithimport.meta.dirnameandrequire.main === modulewith a check ofimport.meta.filenameagainstprocess.argv[1]. - Replace conditional
require()with top-levelawait import(). - Publish dual packages with the
exportsfield's conditions; see Conditional exports.
Usage notes
- A mistaken extension shows up as syntax errors.
Cannot use import statement outside a modulemeans a CommonJS file usedimport;require is not defined in ES module scopemeans the reverse. - Live bindings mean an exported
letchanged by the exporter is seen updated by importers, whichmodule.exportscopies 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.