Node.js Modules
Node.js Modules: CommonJS vs ES Modules Explained
Node.js modules split an application into small, self-contained files where variables stay private unless explicitly exported. Breaking routing, database queries, and formatting helpers into separate modules prevents global namespace conflicts and simplifies unit testing.
CommonJS (require) vs ES Modules (import)
Node.js supports two module systems: the classic CommonJS (CJS) format used in legacy codebases and the JavaScript-standard ES Modules (ESM) format used in modern Node.js projects.
| Feature | CommonJS (.cjs / default) |
ES Modules (.mjs or "type": "module") |
|---|---|---|
| Import Syntax | const fs = require('node:fs') |
import fs from 'node:fs' |
| Export Syntax | module.exports = { fn } |
export function fn() {} |
| Loading Mode | Synchronous at runtime | Asynchronous static graph |
Top-Level await |
Not supported | Supported natively |
| Path Globals | __dirname, __filename |
import.meta.dirname (Node 20.11+) |
Writing and Importing Local Modules
In an ES module project ("type": "module" in package.json), always include the .js file extension on relative local imports (./math.js).
// tax.js (ES Module)
export function addSalesTax(amount, rate = 0.08) {
return Number((amount * (1 + rate)).toFixed(2));
}
// checkout.js
import { addSalesTax } from './tax.js';
console.log('Total due:', addSalesTax(49.5));
In a CommonJS file, assign public functions to module.exports and load them with require('./tax').
// tax.cjs (CommonJS)
function addSalesTax(amount, rate = 0.08) {
return Number((amount * (1 + rate)).toFixed(2));
}
module.exports = { addSalesTax };
Common Mistakes to Avoid
- Omitting
.jsin ESM relative imports: Writingimport { helper } from './helper'throwsERR_MODULE_NOT_FOUNDin native Node.js ESM. Always include.js. - Reassigning
exports = myFuncin CommonJS: Reassigningexportsbreaks the reference tomodule.exportsand exports an empty object{}. Always assignmodule.exports = myFunc. - Forgetting
node:prefix on built-in modules: Always writeimport path from 'node:path'so Node never accidentally resolves a malicious third-party package namedpath.
Frequently Asked Questions
Should new Node.js projects use CommonJS or ES Modules?
Use ES Modules ("type": "module" in package.json). ESM matches browser JavaScript and TypeScript standards, enables top-level await, and supports cleaner tree-shaking.
How do I get __dirname inside an ES module?
In Node.js 20.11+, read import.meta.dirname directly. In older Node 18/20 releases, compute it via path.dirname(fileURLToPath(import.meta.url)).
Can an ES module import a CommonJS package from npm?
Yes. ESM files can import almost any CommonJS npm package via default import (import pkg from 'cjs-pkg').
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.