CommonJS modules
How require and module.exports work in Node, the wrapper function around every file, exports versus module.exports, the module cache, and cycles.
CommonJS modules
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Node wraps every CommonJS file in a function that receives `exports`, `require`, `module`, `__filename` and `__dirname`. That is why those names exist in every file without being declared, and why top-level `var` and `function` do not leak between files.
- `require()` returns whatever the target file assigned to `module.exports`. `exports` is only a shortcut that starts out pointing at the same object, so assigning to `exports` directly changes nothing for the caller.
- Modules are loaded once and cached by resolved filename. Every `require` of the same file returns the same object, which makes a module a natural singleton and means its top-level code runs only once.
- `require` is synchronous and can be called anywhere, including inside `if` blocks and functions. That flexibility is what ES modules deliberately gave up in favour of static analysis.
- When two modules require each other, the second one receives the first's partially filled `exports`, not an error. The usual fix is to restructure so the cycle does not exist.
Why modules exist at all
The browser’s first answer to sharing code between files was <script> tags that all wrote into one shared global scope. Two files that both declared var user overwrote each other. Node was built for servers with many files, so it needed each file to have its own private scope and a clear way to say what it offers to others. The answer, borrowed from a community spec called CommonJS, is: every file is a module, it exposes things by assigning to module.exports, and other files pull them in with require.
// math.js
const PI = 3.14159; // private to this file
function area(r) { return PI * r * r; }
module.exports = { area }; // the public surface
// app.js
const { area } = require('./math');
console.log(area(2));
PI is invisible in app.js. That privacy is not magic; it comes from a function.
The wrapper function
Before running your file, Node wraps its contents in a function and calls it. The effect is as if your file were written like this:
(function (exports, require, module, __filename, __dirname) {
// your file's code here
});
This explains four things at once. require, module, exports, __filename and __dirname are not globals; they are parameters of that function, which is why they exist in every CommonJS file with no declaration. Top-level const, let, var and function in your file are local to the function, so they cannot collide with another file’s. A top-level return is legal in a CommonJS file, because it is returning from the wrapper. And this at the top level of a module is module.exports. You can check it:
console.log(typeof require, typeof module, typeof exports, typeof __filename, typeof __dirname);
console.log(this === module.exports, exports === module.exports); // true true
console.log(arguments.length); // 5
That last line prints 5 because there really are five arguments.
exports versus module.exports
exports starts out as another name for module.exports. Both point at the same object, and require hands back module.exports. That is the whole story, and it produces the classic bug:
exports = { lost: true }; // rebinds the local variable only
module.exports.kept = true;
console.log(module.exports); // { kept: true }
Reassigning exports points the local name at a new object. module.exports still points at the original, and that is what require returns. The rules of thumb:
- To add named exports one at a time, use
exports.name = value(this mutates the shared object, so it works). - To export a single thing such as a function or a class, assign
module.exports = thing. - Do not mix the two styles in one file. If you assign
module.exports, the earlierexports.x = ...lines are lost.
The module cache
require resolves the path, loads the file once, runs it, and stores the result in require.cache, keyed by the resolved filename. Later calls return the stored object:
// counter.js
let n = 0;
console.log('counter.js is running');
module.exports = { next: () => ++n };
// cache.js
const a = require('./counter');
const b = require('./counter');
console.log(a === b, a.next(), b.next()); // true 1 2
counter.js is running prints once, and a and b are the same object, so the counter is shared. That makes a CommonJS module a natural singleton: a database connection or configuration object created at the top of a module is created once for the whole process. The same rule means module-level state is shared between every part of your program that imports it, which is useful and also a source of test pollution.
You can evict an entry with delete require.cache[require.resolve('./counter')] and the next require loads a fresh copy, which resets the counter. That is an escape hatch for tests and hot reload, not something to build on.
Synchronous and dynamic
require blocks until the file is read and run. It can sit anywhere: inside an if, inside a function, with a computed string. That freedom is why tools cannot always know the full dependency graph ahead of time. ES modules, covered in ES modules in Node and interop, traded it away for static import statements that tools and engines can analyse. Because require is synchronous, a heavy top-level require slows startup, a theme in blocking vs non-blocking I/O.
Cycles
If a.js requires b.js while b.js requires a.js, Node does not fail. It returns the partly finished exports of the module that is still running:
// a.js
console.log('a starts'); exports.done = false;
const b = require('./b');
console.log('in a, b.done =', b.done); exports.done = true;
// b.js
console.log('b starts'); exports.done = false;
const a = require('./a');
console.log('in b, a.done =', a.done); exports.done = true;
Running node a.js prints a starts, b starts, in b, a.done = false, in a, b.done = true. b saw a before a finished. Cycles that work by accident are fragile. Break them by moving the shared piece into a third module, or by requiring lazily inside the function that needs it.
What the video covers
Codevolution’s video is about module.exports versus exports, the confusion above, with working examples. His separate “Module Wrapper” video, linked under “go deeper”, explains the wrapper function. Neither covers the module cache or cycles as far as their titles show, and no transcript was available, so those two sections are carried by the prose, each run against Node 26.13.1. Both videos date from December 2022, and nothing in CommonJS has changed since.
Where this fits
CommonJS is still the format of much of npm, so you will read and require it for years even in ES-module projects. Next is the other module system and how the two meet: ES modules in Node and interop. How require('./math') finds the file is in how Node resolves modules.
Check yourself
You write `exports = { add }` at the bottom of `math.js`, and `require('./math')` returns `{}`. Why?
`exports` is a local variable that starts out as a reference to `module.exports`. Reassigning it points the local variable somewhere new and leaves `module.exports` untouched, and `require` returns `module.exports`. Write `module.exports = { add }`, or attach properties with `exports.add = add`.
A file contains `console.log('loaded')` and is required from three other files. How many times does it print, and why?
Once. The first `require` runs the file and stores `module.exports` in `require.cache` under the file's resolved path. The later calls return the cached object without running the file again.
Why can you use `__dirname` in a CommonJS file without declaring it?
Node wraps the file in a function that takes `exports, require, module, __filename, __dirname` as parameters. They are local variables of that function, passed in by the loader.
In a cycle where `a.js` requires `b.js` and `b.js` requires `a.js`, what does `b.js` get when it requires `a.js`?
Whatever `a.js` had exported at the moment it called `require('./b')`, which is usually an empty or partly filled object. `a.js` has not finished running, so values it sets after that line are missing from what `b.js` captured.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.