Explain it simply
Explain it simply
A module is like a locked toolbox. It may hold many tools inside, but other people can only take the tools you put on the counter (module.exports).
When another file asks for the box with require(), Node opens it once and hands over whatever is on the counter. Ask again later and you get the very same tools back, not a fresh copy. Everything left inside the box stays hidden, so you can rearrange it without bothering anyone.
Problem → Why → Solution
The problem: a thousand lines in one file
At the start of a project it is easy to put everything into one app.js. Six months later it has thousands of lines: functions are hard to find, variable names collide, and fixing one thing breaks something unrelated. The first attempt to split it usually trips over the two errors below.
// mathTools.js ended with: exports = { add, multiply };
const mathTools = require("mathTools"); // no ./ in front
console.log(mathTools.add(5, 3));
// Error: Cannot find module 'mathTools'
// ...and after adding ./ : TypeError: mathTools.add is not a functionWhy does this happen?
Node treats a specifier without ./ as a package name and searches node_modules for it. And exports = {...} only reassigns a local variable, so the module.exports object that require() returns stays empty. Knowing a few CommonJS rules makes both errors disappear.
Core concept: one file, one scope; module.exports is the public API
CommonJS is Node's original module system. Before running a .js file, Node wraps it in a function: (function (exports, require, module, __filename, __dirname) { ...your code... }). That is why every variable you declare in a file is private to that file, and why require, module and __dirname are function parameters rather than true globals.
When you call require("./mathTools"), Node resolves the path, runs the file once and returns whatever ended up in module.exports. The module is cached under its fully resolved filename, so a second require does not run the file again; it returns the same object. That is why something that should exist only once, such as a database connection pool, is created inside a module and shared by the whole app. require() is synchronous: the next line runs only after the file has loaded.
exports is just a shortcut variable pointing at module.exports. exports.add = add puts a property on that object and works, but exports = { add } merely points the shortcut at a new object, while Node still returns module.exports. To export a whole object, write module.exports = { add }.
When does Node treat a file as CommonJS? A .cjs file always is, and a .js file is too unless the nearest package.json says "type": "module". module.exports can hold more than an object: a single function, a class or even a string. With module.exports = class Cart {...}, require() returns the class itself. JSON files can be loaded with require("./data.json") as an already-parsed object.
| Specifier | Where Node looks |
|---|---|
| "node:fs" | The built-in module shipped with Node (prefer this explicit form) |
| "./mathTools" | Relative to the requiring file's folder: mathTools, then .js, .json, then folder/index.js |
| "express" | node_modules/express, searching upward from the current folder |
- Resolve the specifier to a file
- Check the module cache
- If new, run the file in its wrapper
- Cache and return module.exports
A module's code runs at most once per process.
General pattern: CommonJS export and import
// some-module.js
const privateValue = 1; // stays inside this file
function publicName(param) { /* ... */ }
module.exports = { publicName };
// consumer.js
const { publicName } = require("./some-module");
const builtIn = require("node:module-name");In the module, assign module.exports once and include only what outsiders should use. In the consumer, destructure what require() returns. Always start your own files with ./ and built-ins with node:.
Example: load a real module file and watch the cache
So that two files can be tried with one command, this script writes mathTools.js into a temporary folder and loads it twice with require(). Watch the module's log appear only once, both requires return the same object, and the private variable stay invisible from outside. The temporary folder is deleted at the end.
// modules-demo.js - CommonJS: module.exports and require()
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
// Write a real module file into a fresh temporary folder.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cjs-demo-"));
const mathFile = path.join(dir, "mathTools.js");
fs.writeFileSync(mathFile, `
console.log("mathTools.js runs (only once)");
let calls = 0; // private to this file
function add(a, b) { calls++; return a + b; }
function multiply(a, b) { calls++; return a * b; }
module.exports = { add, multiply, callCount: () => calls };
`);
const mathTools = require(mathFile);
const sameModule = require(mathFile);
console.log(mathTools.add(5, 3));
console.log(mathTools.multiply(5, 3));
console.log("Second require returns the same object:", mathTools === sameModule);
console.log("Calls so far:", mathTools.callCount());
console.log("Can this file see calls?", typeof calls);
fs.rmSync(dir, { recursive: true, force: true });Code breakdown
- Lines 2-4
const fs = require("node:fs");Built-in modules are required with the node: prefix. fs, os and path are used here only to create a temporary file.
- Line 14
module.exports = { add, multiply, callCount: () => calls };This is mathTools.js's public API. Instead of exporting the calls variable itself, it exposes a read-only callCount() function, so outsiders cannot change the count.
- Lines 17-18
const sameModule = require(mathFile);The first require runs the file, so the "runs (only once)" log appears. The second one returns the cached object and logs nothing. In a normal project you would write require("./mathTools") with a relative path.
- Line 22
mathTools === sameModuletrue means both variables point at one object, which is also why the calls counter is shared between them.
- Line 24
typeof callscalls was declared inside mathTools.js's wrapper function, so this file cannot see it and typeof gives "undefined".
mathTools.js runs (only once)
8
15
Second require returns the same object: true
Calls so far: 2
Can this file see calls? undefinedThe two-file layout you write in a project
In a real project you skip the temporary file: put mathTools.js and app.js in the same folder and run node app.js. The ./ in "./mathTools" means the folder containing app.js, not the terminal's current folder, and require() fills in the missing .js extension for you.
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = { add, multiply };const { add, multiply } = require("./mathTools");
console.log(add(5, 3)); // 8
console.log(multiply(5, 3)); // 15exports versus module.exports, tested directly
This snippet shows what happens when the shortcut variable is replaced with a new object. module.exports keeps only add, while multiply disappears into a local object nobody else can see.
// exports-alias.js - why "exports = ..." silently does nothing
const { strict: assert } = require("node:assert");
assert.ok(exports === module.exports); // two names, one object
exports.add = (a, b) => a + b; // adds a property: works
exports = { multiply: (a, b) => a * b }; // rebinds the local name only
console.log("module.exports keys:", Object.keys(module.exports));
console.log("local exports keys:", Object.keys(exports));In real projects
Where you meet CommonJS in real projects
The Node ecosystem grew up on CommonJS, so many npm packages and most existing Express apps still use require(). Tool configuration files such as .eslintrc.cjs and jest.config.js often contain module.exports = {...}. ES modules are increasingly common, but you need CommonJS to read and debug existing code, and job interviews still ask about it.
Projects are usually split into modules by responsibility: routes/users.js holds HTTP routes, services/userService.js holds business logic, and db.js exports a single database connection that the whole app shares thanks to the module cache. The smaller each public API, the easier the module is to test and the safer it is to change its internals without breaking the files that use it.
Common mistakes
Common mistakes
1. Leaving out ./ for your own file
require("mathTools") is read as a package name, searched for in node_modules, and fails with "Cannot find module 'mathTools'". Always require project files with a relative path such as "./mathTools" or "../lib/mathTools".
2. Replacing exports with a new object
exports = { add } throws no error and exports nothing; the problem only shows up later as "add is not a function" in the consumer. Write exports.add = add for single properties, or module.exports = { add } for a whole object.
3. Two modules requiring each other
If a.js requires b.js and b.js requires a.js (a circular dependency), b.js receives a.js's half-finished exports and its functions are often undefined. Move the shared code into a third module that both can require.
Best practices
Best practices
- Group every require() call at the top of the file so its dependencies are visible at a glance.
- Assign module.exports once, at the end of the file, so the public API can be read in one place.
- Give each module one job; wanting to name it with "and" is a sign it should be split.
- Avoid side effects at require time, such as starting a server or writing files; wrap them in a function and let the caller decide.
Mini challenge
Mini challenge: a calculator module that tests itself
Write calculator.js that exports only add and divide, with a private helper that validates input. Run directly with node calculator.js, it tests itself; required from another file, it prints nothing.
- Do not export the assertNumber() helper
- Throw a TypeError for non-numbers and a RangeError for division by zero
- module.exports must be exactly { add, divide }
- Run the self-test only when require.main === module
// calculator.js - a CommonJS module that can also test itself
const assert = require("node:assert/strict");
function assertNumber(value, name) {
// TODO: throw a TypeError unless value is a real number (not NaN)
}
function add(a, b) {
// TODO: validate both arguments, then return the sum
}
function divide(a, b) {
// TODO: validate, throw a RangeError when b is 0, return a / b
}
// TODO: export only add and divide
// TODO: if this file is the entry point (require.main === module):
// assert add(2, 3) is 5, print a few results, catch and print two errors,
// and print the exported namesExpected: Running node calculator.js prints: add(2, 3) = 5 divide(10, 4) = 2.5 RangeError: Cannot divide by zero TypeError: a must be a number, got string Public API: add, divide
Show hint
require.main is the module that node was started with. When another file requires this one, require.main is that other file, so the condition is false. Print errors as err.name plus err.message.
Show solution
// calculator.js - a CommonJS module that can also test itself
const assert = require("node:assert/strict");
function assertNumber(value, name) {
if (typeof value !== "number" || Number.isNaN(value)) {
throw new TypeError(`${name} must be a number, got ${typeof value}`);
}
}
function add(a, b) {
assertNumber(a, "a");
assertNumber(b, "b");
return a + b;
}
function divide(a, b) {
assertNumber(a, "a");
assertNumber(b, "b");
if (b === 0) throw new RangeError("Cannot divide by zero");
return a / b;
}
module.exports = { add, divide };
// True only when run as `node calculator.js`, not when another file requires it.
if (require.main === module) {
assert.equal(add(2, 3), 5);
console.log("add(2, 3) =", add(2, 3));
console.log("divide(10, 4) =", divide(10, 4));
for (const bad of [() => divide(1, 0), () => add("2", 3)]) {
try {
bad();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}
console.log("Public API:", Object.keys(module.exports).join(", "));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Each CommonJS file runs inside a wrapper function, so its variables are private.
- require() returns module.exports; a module runs once, on first load, and is then cached.
- exports.x = ... works, exports = {...} exports nothing; use module.exports = {...} for whole objects.
- Require your files with ./, built-ins with node:, and packages by bare name.
CommonJS modules — Node.js