Intermediate · 14 of 17 · 15 min read
CommonJS and require
Node's original module system, why require returns a cached copy, and the differences from ES modules that actually bite.
- Modules
CommonJS is the module system Node shipped with, years before the language had one. It is still everywhere — in dependencies, in config files, in older codebases — so reading it is a working skill even if you write ES modules exclusively.
Exporting
module.exports is the object the file hands back. Anything you put on it is public:
// math.js
const PI = 3.14159;
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
module.exports = { PI, add, subtract };
// app.js
const math = require('./math'); // the extension is optional in Node
const { add, PI } = require('./math'); // destructure what you need
console.log(math.add(1, 2), add(1, 2), PI); // 3 3 3.14159
You can also export a single value — the closest thing to a default export:
// logger.js
module.exports = function log(message) {
console.log(`[app] ${message}`);
};
// app.js
const log = require('./logger');
log('started');
Or attach exports one at a time:
// utils.js
exports.trim = (s) => s.trim();
exports.upper = (s) => s.toUpperCase();
// equivalent to module.exports.trim = …
The exports trap
exports starts out as a reference to module.exports. Attaching properties to it works, because
both names point at the same object. Reassigning it breaks the link:
// broken.js
exports = { a: 1 }; // now a local variable — module.exports is still {}
// require('./broken') gives {}
// works.js
module.exports = { a: 1 }; // replaces the real thing
exports.b = 2; // ignored — exports no longer points at module.exports
// require('./works') gives { a: 1 }
The rule: use module.exports when you are replacing the whole export, and exports.x only
when adding to it. Picking one and sticking to it avoids the question entirely.
The require cache
A module is evaluated once per resolved path. Every later require of the same file gets the
same exported object straight out of the cache:
// counter.js
console.log('counter evaluated');
let count = 0;
module.exports = {
increment() { count += 1; return count; },
get current() { return count; },
};
// app.js
const a = require('./counter'); // logs "counter evaluated"
const b = require('./counter'); // nothing logged — cached
console.log(a === b); // true — the same object
a.increment();
console.log(b.current); // 1 — a and b are one module
That is what makes a CommonJS module a singleton, and it is the mechanism behind the module pattern:
state in the closure, a small surface on module.exports.
console.log(Object.keys(require.cache).length > 0); // the cache is inspectable
// delete require.cache[require.resolve('./counter')]; // forces a re-evaluation
Deleting from the cache is a test-only trick. In application code it creates two copies of a module that was meant to be one, which is a confusing class of bug.
A copy, not a live binding
require returns the value of module.exports at the moment it ran. If the module later
reassigns a primitive export, the importer never sees it:
// value.js
let count = 0;
module.exports.count = count;
module.exports.increment = () => {
count += 1;
module.exports.count = count; // has to be re-published explicitly
};
const mod = require('./value');
console.log(mod.count); // 0
mod.increment();
console.log(mod.count); // 1 — only because the module reassigned the property
Destructuring makes the snapshot permanent, which is the bug this causes in practice:
const { count } = require('./value'); // a copy of the number, forever 0
In ES modules, import { count } would track the change. This is the sharpest behavioural
difference between the two systems — and the reason a CommonJS module that must expose changing
state exposes a function instead of a value.
What else is in scope
Every CommonJS file is wrapped in a function before it runs, which is where its five free variables come from:
// what Node effectively does:
// (function (exports, require, module, __filename, __dirname) { … your file … });
console.log(typeof require, typeof module); // "function" "object"
console.log(__filename.endsWith('.js')); // true — the absolute path of this file
console.log(typeof __dirname); // "string" — its directory
console.log(module.exports); // {} before you assign anything
That wrapper is also why a CommonJS file has its own scope without needing one, and why this at the
top level is module.exports rather than undefined:
console.log(this === module.exports); // true in CommonJS
In ES modules __dirname and __filename do not exist. The replacements:
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const here = dirname(fileURLToPath(import.meta.url)); // the __dirname equivalent
console.log(typeof import.meta.url); // "string"
require is dynamic
Because it is just a function call, it can go anywhere a call can:
function loadDriver(name) {
return require(`./drivers/${name}`); // a computed path, resolved when this runs
}
if (process.env.NODE_ENV !== 'production') {
const devTools = require('./dev-tools'); // conditional, and synchronous
}
The cost is that nothing can be known ahead of time: a bundler cannot tree-shake what it cannot see,
and a typo in the path is a runtime crash rather than a build error. ES modules trade that
flexibility for analysability, and add import() for the cases that genuinely need it.
Side by side
| CommonJS | ES modules | |
|---|---|---|
| Syntax | require / module.exports |
import / export |
| Resolved | at runtime, when the call runs | before execution |
| Loading | synchronous | asynchronous |
| Exports are | a snapshot of the object | live bindings |
| Conditional / computed paths | yes | only via import() |
Top-level await |
no | yes |
Top-level this |
module.exports |
undefined |
| Strict mode | opt in | always |
__dirname / __filename |
yes | no — use import.meta.url |
| Tree shaking | poor | good |
| Browser support | none without a bundler | native |
Mixing the two
Node lets an ES module import a CommonJS one. The whole module.exports arrives as the default:
// esm.mjs
import cjs from './legacy.cjs'; // module.exports
import { named } from './legacy.cjs'; // sometimes works, via static analysis
console.log(typeof cjs);
The other direction does not work synchronously, because an ES module may contain top-level await:
// legacy.cjs
// const esm = require('./module.mjs'); // ERR_REQUIRE_ESM in older Node versions
const esm = await import('./module.mjs'); // the portable way, inside an async function
Which file is which: .mjs is always an ES module, .cjs is always CommonJS, and a plain .js
follows the nearest package.json — "type": "module" makes it ESM, and its absence makes it
CommonJS.
{
"type": "module"
}
Common mistakes
Reassigning exports
Mistake. exports = { api }.
Why it fails. It rebinds a local variable, so module.exports is still the empty object the
wrapper created and the module exports nothing.
What to do instead. module.exports = { api }.
Destructuring a value that changes
Mistake. const { config } = require('./state') for something reassigned later.
Why it fails. You captured the value at require time; CommonJS exports are not live.
What to do instead. Keep the module object (const state = require('./state')) and read
state.config, or export a getter function.
Assuming require works in an ES module
Mistake. Calling require in a .mjs file or under "type": "module".
Why it fails. require is not defined there — it is a variable of the CommonJS wrapper.
What to do instead. Use import, or build one with
createRequire(import.meta.url) from node:module when you genuinely need the CommonJS resolver.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
In CommonJS, what does the second require("./m") in a process return?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.