Modules (CommonJS & ES Modules)
require, module.exports, import/export, and how resolution works.
Why modules exist
Real programs are too big for one file. Modules let you split code into files that each expose a small, deliberate surface and hide everything else. In Node.js, every file is a module with its own private scope — variables you declare at the top level of a file are *not* global; they belong to that file alone.
Node supports two module systems:
- CommonJS (CJS) — the original Node system:
require()andmodule.exports. Files use the.cjsextension, or.jsin a default project. - ES Modules (ESM) — the JavaScript standard:
importandexport. Files use.mjs, or.jswhen package.json contains"type": "module".
// A top-level variable in a module is NOT global.
const secret = "only visible in this file";
// Inside a CommonJS module, "module" describes the current module:
console.log("Am I the entry script?", require.main === module);
console.log(secret);CommonJS: require and module.exports
In CommonJS, a module exposes values by assigning to module.exports, and consumers pull them in with require(). Whatever module.exports holds when the file finishes running is what require returns.
Two common export styles:
- Export an object of named things:
module.exports = { add, subtract }— consumers destructure what they need - Export one main thing:
module.exports = MyClass— consumers get it directly
exports (without module.) is a shorthand alias for the same object, so exports.add = ... works — but reassigning exports = ... breaks the link and exports nothing. When in doubt, use module.exports.
// ---- math.js ----
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
module.exports = { add, subtract };
// ---- app.js ----
const { add, subtract } = require("./math");
console.log(add(2, 3)); // 5
console.log(subtract(9, 4)); // 5ES Modules: import and export
ES Modules are the official standard used by browsers and modern Node alike. You mark values with export and bring them in with import. Node treats a file as ESM when it ends in .mjs or when the nearest package.json has "type": "module".
Key differences from CommonJS:
- Imports are static — declared at the top, analyzable before the code runs
- Imports are resolved asynchronously, and ESM files may use top-level
await - In ESM there is no
require, nomodule.exports, and no__dirname(useimport.meta.urlinstead) - A
defaultexport gives the module one main value; named exports give it several
// ---- math.mjs ----
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// ---- app.mjs ----
import multiply, { add } from "./math.mjs";
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20How Node resolves what you require
When you call require(x) (or import x), Node figures out which file to load using these rules:
- Starts with `./` or `../` or `/` — a file path relative to the current file. Node tries the exact name, then adds extensions (
.js,.json,.node), then looks for a directory with anindex.js. - A bare name like `express` — first Node checks its built-in modules (
fs,path,http...), then walks up the directory tree looking in eachnode_modulesfolder until it finds the package. - Prefixed with `node:` — explicitly a builtin, e.g.
require("node:fs"); this skips node_modules entirely.
A loaded module is cached: the second require of the same file returns the same object instantly, without re-running the file.
// Bare names check builtins first:
const path = require("path");
const os = require("os");
console.log(path.join("src", "lib", "utils.js"));
console.log("Home directory:", os.homedir());
// The node: prefix makes builtin intent explicit:
const assert = require("node:assert");
assert.strictEqual(1 + 1, 2);
console.log("assert passed - resolution works!");Module caching in practice
The first require of a module runs its code and stores the exports in a cache keyed by the resolved filename. Every later require of that file gets the cached exports object — the module's code runs exactly once.
This has a useful consequence: a module can hold shared state. If counter.js exports an object, every file that requires it sees the *same* object, making modules a lightweight way to share configuration or a single database connection across an app.
// Requiring the same builtin twice returns the same object:
const events1 = require("events");
const events2 = require("events");
console.log("Same cached object?", events1 === events2); // true
// This is why a module can act as shared state:
// every consumer gets the SAME exports object.Check your understanding
5 questionsQuestion 1 of 5
Score: 0