CommonJS: require and module.exports
Before ES modules, JavaScript had no imports at all, and Node.js filled the gap with CommonJS: require loads a file and returns whatever it put on module.exports. The folder of this lesson has no package.json with "type": "module", so Node.js reads every .js file in it as CommonJS.
That is the reason this lesson uses CommonJS rather than the ES modules of the lesson before: it is still the format of a large part of the packages on npm, it needs no configuration, and a program that has to load one of those packages meets it. The difference between require and import is worth knowing before reading someone else. The two systems do not share a file.
require and module.exports
Every CommonJS file gets a module object, and module.exports is what a caller receives. require with a path that starts with ./ loads the file, runs it once, and returns that object. The counter below keeps its number in the module and offers a function and a getter, so the caller can change it and read it but not replace it.
The file count.js:
let count = 0;
function bump() {
count += 1;
return count;
}
module.exports = {
bump,
get count() {
return count;
},
};
The file app.js:
const counter = require('./count.js');
console.log('the first bump:', counter.bump());
console.log('the second bump:', counter.bump());
console.log('the count:', counter.count);
console.log('the module exported an object:', typeof counter);
node app.js
the first bump: 1
the second bump: 2
the count: 2
the module exported an object: object
Two calls to one function and one read of the getter, all on the object the module returned. The count is module state: it lives in the closure of the file and not on the object, so nothing outside can write it directly. A getter in the exported object is a CommonJS idiom for a read-only field, and the function is the only way to change the number.
The module cache
The first require of a file runs it, and every later one returns the object from a cache rather than running the file again. The cache is keyed by the resolved path, so two files that require the same module share one instance of it, which is how a module becomes the one place where state lives. The log line in shared.js is there to prove it ran once.
The file shared.js:
console.log('shared.js is evaluated');
let hits = 0;
module.exports = {
bump() {
hits += 1;
return hits;
},
get hits() {
return hits;
},
};
The file a.js:
const shared = require('./shared.js');
shared.bump();
shared.bump();
module.exports = shared;
The file main.js:
const fromA = require('./a.js');
const shared = require('./shared.js');
console.log('the same object twice:', fromA === shared);
console.log('the hits counted in a.js:', shared.hits);
console.log('one more from here:', shared.bump());
console.log('and through the other name:', fromA.hits);
node main.js
shared.js is evaluated
the same object twice: true
the hits counted in a.js: 2
one more from here: 3
and through the other name: 3
The line from shared.js appeared once, though three files asked for it. The object was the same one in both places, so the two bumps from a.js and the one from the program added up to three. This sharing is a feature and a trap: a module that keeps state is a singleton, and a test that expects a fresh one has to clear the cache or start a new process.
exports is not module.exports
Node.js runs a CommonJS file inside a function whose parameters are exports, require, module, __filename and __dirname. At the start exports and module.exports point at the same object, so adding a property to exports works. Assigning a new object to exports only moves the local parameter, and the caller keeps the old object. The file below writes that wrapper out so the reassignment is visible.
The file trap.js:
// Node runs this file inside a function whose first parameter is exports.
(function run(exports) {
exports.name = 'kept';
exports = { name: 'lost' };
exports.note = 'added after the reassignment';
module.exports.kind = 'object';
})(exports);
The file use-trap.js:
const trap = require('./trap.js');
console.log('what the caller gets:', JSON.stringify(trap));
console.log('the name that survived:', trap.name);
console.log('the object that was reassigned:', trap.kind);
node use-trap.js
what the caller gets: {"name":"kept","kind":"object"}
the name that survived: kept
the object that was reassigned: object
The caller received the object module.exports points at, with the field that was added before the reassignment and the one added through module.exports. Everything written to exports after the reassignment went to the object named lost, and nobody ever saw it. The rule that follows: add to exports, or replace module.exports, and never assign to exports itself.
What require returns
module.exports may hold any value, not only an object: a function is a common choice, and the caller then calls what it required. A JSON file needs no parsing, because require reads and parses it. Both cases show the same fact from the other side: the return value is whatever the file assigned.
The file format.js:
function format(name, value) {
return `${name}=${value}`;
}
module.exports = format;
The file data.json:
{
"suite": "parser",
"runs": 3
}
The file use-format.js:
const format = require('./format.js');
const data = require('./data.json');
console.log('a module can export a function:', typeof format);
console.log('and the call works:', format('runs', data.runs));
console.log('JSON needs no parse here:', JSON.stringify(data));
console.log('a second require is the same object:', require('./data.json') === data);
node use-format.js
a module can export a function: function
and the call works: runs=3
JSON needs no parse here: {"suite":"parser","runs":3}
a second require is the same object: true
The function arrived as a value and the call worked, and the JSON file arrived as an object with no parsing step in sight. The last line is the cache again: the second require of the same path returned the same object. A JSON file read this way is cached too, so a change to it needs a restart, which is worth knowing before reading configuration once at start-up.
Exercises
- Export the count itself from count.js instead of a getter and print it after two bumps. Which value does the caller see?
- Add a third file to the cache example that requires shared.js and bumps once. How many log lines does the program print now?
- Change trap.js to module.exports = { name: "lost" } and print the caller value. Which fields arrive?
- Export an array from format.js and print its length in use-format.js. Does the type of the value make any difference to require?
- Require ./data.json twice and change a field between the two calls. Which value does the second call see?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does require return?
Answer
Whatever the file assigned to module.exports
The exports object is the interface, and require hands it back after running the file once.
-
How many times does Node.js run a module that three files require?
Answer
Once, the rest come from the cache
The cache is keyed by the resolved path, so the file is evaluated once per process.
-
Why does
exports = { a: 1 }not change what the caller gets?Answer
It moves a local parameter that module.exports no longer follows
The wrapper parameter is a copy of the reference, so assigning a new object to it changes nothing outside.
-
What can module.exports hold?
Answer
Any value, including a function or an array
The caller gets the value itself, which is why a module can export one function.
-
The file m.js contains:
module.exports = { n: 1 }; const m = require("./m.js"); console.log(m.n);What doesnode m.jsprint?Answer
1
The export is assigned before the require, and the cache returns that object.
-
Two files in one folder, a.js is
module.exports = { n: 1 };and main.js is:const a = require("./a.js"); const b = require("./a.js"); b.n = 2; console.log(a.n, a === b);Answer
2 true
Both calls returned the same cached object, so the write through one name is visible through the other.
-
What does this program print?
exports.a = 1; exports.a = 2; console.log(module.exports.a);Answer
2
Adding to exports adds to the object module.exports points at, and the last write wins.
-
A file f.js is
module.exports = function (n) { return n * 2; };and main.js is:const f = require("./f.js"); console.log(typeof f, f(3));Answer
function 6
module.exports can hold a function, and the caller calls the value it received.
-
A file pair.js is
exports.a = 1; exports = { b: 2 };and main.js printsObject.keys(require("./pair.js")).join(","). What does it print?Answer
a
The reassignment touched only the local parameter, so the caller keeps the object with the one field.
-
The file data.json next to the program holds
{ "suite": "parser", "runs": 3 }. What does this program print?const data = require("./data.json"); console.log(typeof data);Answer
object
require parses a JSON file and returns the object it describes.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev