In Chapter 04: Modules you saw that every file keeps its variables private. In this chapter you'll find out how. The answer is different for the two module systems, so, like Chapter 04, the chapter is split into tabs: ES Modules (part of the language, loaded by V8 and Node.js together, in three phases) and CommonJS (Node.js wraps your file in a function). After the tabs, you'll take a short tour of where all this lives in Node.js's own source code.
In this chapter you'll learn
- how functions create private scope, and what an IIFE is
- ES Modules: why there's no wrapper, the three loading phases (construction, linking, evaluation), and what V8 does vs what Node.js does
- CommonJS: the hidden module wrapper, where
require,module,exports,__filenameand__dirnamecome from, and the five steps ofrequire - how Node.js's source code is organised (JavaScript in
lib/, C++ insrc/)
Before you start: read Chapter 04: Modules.
Functions create private scope
In JavaScript, variables declared inside a function can't be seen outside it. This is called function scope.
function makeCounter() {
let count = 0; // private to this function
return () => ++count;
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
console.log(count); // ReferenceError: count is not definedfunction makeCounter() {
let count = 0; // private to this function
return () => ++count;
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
console.log(count); // ReferenceError: count is not definedIIFE: run a function immediately
An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it's defined. Before modules existed, developers used IIFEs to keep variables out of the global scope.
(function () {
const secret = "only visible in here";
console.log("IIFE ran:", secret);
})();
console.log(typeof secret); // "undefined": it didn't leak out(function () {
const secret = "only visible in here";
console.log("IIFE ran:", secret);
})();
console.log(typeof secret); // "undefined": it didn't leak outThe pattern is: wrap a function in ( ) to make it an expression, then call it straight away with (). IIFEs can take arguments too:
(function (name) {
console.log(`Hello ${name}`);
})("Node.js"); // Hello Node.js(function (name) {
console.log(`Hello ${name}`);
})("Node.js"); // Hello Node.jsKeep this idea in mind: a function gives you a private scope. CommonJS uses exactly this trick for every file. ES Modules don't need it, because the language gives each module its own scope directly.
How ES Modules are loaded: no wrapper at all
ES Modules (import / export, Chapter 04) are part of the JavaScript language itself, so loading them is a job shared by V8 and Node.js, and it explains every ESM behaviour you learned in Chapter 04.
There is no wrapper function. Private file scope is built into the JavaScript language itself for modules, so V8 gives every ES Module its own scope directly. You can prove it: the wrapper's parameters simply aren't there.
// proof.mjs
console.log(typeof arguments); // "undefined": no wrapper function around this file
console.log(typeof require); // "undefined"
console.log(this); // undefined (CommonJS: module.exports)
console.log(import.meta.dirname); // the ESM replacement for __dirname// proof.mjs
console.log(typeof arguments); // "undefined": no wrapper function around this file
console.log(typeof require); // "undefined"
console.log(this); // undefined (CommonJS: module.exports)
console.log(import.meta.dirname); // the ESM replacement for __dirnameInstead of one require call doing everything at once, an ES Module graph is loaded in three phases, and no code runs until the first two are finished for every file:
Evaluation order follows the graph: dependencies first, in the order they're imported. If app.js imports a.js then b.js, and a.js imports c.js:
// app.js
import "./a.js"; // a.js imports c.js
import "./b.js";
console.log("app.js runs");// app.js
import "./a.js"; // a.js imports c.js
import "./b.js";
console.log("app.js runs");c.js runs
a.js runs
b.js runs
app.js runsc.js runs
a.js runs
b.js runs
app.js runsWho does what: V8 vs Node.js
Because import / export are defined by the ECMAScript standard, the engine does the core work. Node.js only does the parts the standard leaves to the "host" (the program that embeds V8):
| Job | Done by |
|---|---|
Turning "./sum.js" or "express" into a full file:// URL (resolution) | Node.js |
| Reading the file from disk, and turning JSON or CommonJS files into modules | Node.js |
| Remembering loaded modules (the module map, Node's cache) | Node.js |
| Parsing the code into a Module Record: its own scope, its list of imports and exports | V8 |
| Linking: connecting every import to the exported variable it refers to | V8 (it asks Node to resolve each import while it links) |
Evaluating: running the code, handling top-level await | V8 (evaluation returns a Promise) |
Filling in import.meta and loading import() on demand | Node.js, when V8 asks for it |
In Node's C++ code, each ES Module is a ModuleWrap object (src/module_wrap.cc) holding V8's v8::Module. When V8 links a module, it calls back into Node with "where is ./sum.js?"; when your code runs import(), V8 asks Node to load that module; and the first time a module uses import.meta, V8 asks Node to fill it in. So scope, live bindings, hoisting and evaluation order come from V8 and the language spec, while paths, files and caching come from Node.js.
Compare that with CommonJS, where V8 knows nothing about modules: Node.js does everything itself, using an ordinary function (the wrapper) to get a private scope. Open the CommonJS tab to see how.
Common mistakes with ES Modules
- Thinking ES Modules are just
requirewith new syntax. They're loaded in three phases: all imports are found and linked before any code runs, which is why imports are hoisted, must be static, and give live bindings. - Expecting
__dirname,requireormoduleto exist. There's no wrapper to provide them. Useimport,import()andimport.meta.dirname. - Expecting a module to run again when it's imported a second time. It won't; it's in the module map. If you need fresh state each time, export a function that creates it.
- Expecting errors to appear "at that line". A missing file or a missing named export is found during construction or linking, so the program fails before any code runs, even code written above the broken
import.
Key takeaways: ES Modules
- No wrapper: module scope is part of the JavaScript language, and V8 creates it.
- Loading happens in three phases, construction → linking → evaluation, so the whole graph is known and linked before any code runs. That's where hoisting, live bindings and top-level
awaitcome from. - V8 parses, links and evaluates modules; Node.js resolves paths, reads files, keeps the module map and fills in
import.meta. - Modules run once, dependencies first, and are cached by URL.
Interview questions: ES Modules
Q1. Does Node.js wrap ES Modules in a function like CommonJS modules?
No. Module scope is a built-in feature of JavaScript for ES Modules, so V8 gives each module its own scope directly. That's why require, module, exports, __filename, __dirname and even arguments don't exist at the top of an ES Module, and why top-level this is undefined. ESM gets file information from import.meta (import.meta.url, import.meta.dirname, import.meta.filename) instead.
Q2. What are the phases of loading an ES Module?
- Construction: resolve every specifier to a URL, read and parse each file, and follow its imports recursively until the whole module graph is known. No code runs.
- Linking: create a slot for every export and point every import at the exporting module's slot (this is what makes imports live bindings).
- Evaluation: run each module's top-level code once, dependencies first, filling the slots.
Because errors like a missing file or a missing named export are found during construction or linking, an ESM program fails before running any of its code, while CommonJS fails at the require line.
Q3. In what order do ES Modules run?
Depth-first, dependencies before the module that imports them, in the order the import statements appear. If app.js imports a.js then b.js, and a.js imports c.js, the order is c.js, a.js, b.js, app.js. Each module runs only once, even if it's imported from many places. This is also why console.log lines written above an import still run after the imported module.
Q4. Which parts of ES Module loading does V8 do, and which does Node.js do?
import/export are part of the ECMAScript standard, so V8 implements the module semantics: parsing a file into a Module Record (with its own scope), linking imports to exports (live bindings) and evaluating the code (including top-level await). Node.js is the host: it resolves specifiers to URLs, reads files, converts JSON and CommonJS into modules, keeps the module map (cache), and fills in import.meta and dynamic import() when V8 asks. With CommonJS, V8 isn't involved in module handling at all: Node does everything with the wrapper function.
Q5. What is the value of this at the top level of an ES Module, and why?
undefined. ES Modules always run in strict mode, and their top-level code isn't run as a function call with a this value; V8 runs it directly in the module's own scope. (In CommonJS it's module.exports, because the wrapper function is called with this set to it.)
The module wrapper: how Node.js makes files private
Here's the trick. Before running any CommonJS file, Node.js wraps your entire code in a function that looks like this:
(function (exports, require, module, __filename, __dirname) {
// ...your whole file goes here...
});(function (exports, require, module, __filename, __dirname) {
// ...your whole file goes here...
});Then it calls that function. Because your code is now inside a function, every const, let, var and function you declare is local to it. That's exactly the "room with a closed door" from Chapter 04: module.export & require.
This also answers a question that confuses many beginners: where do require, module, exports, __filename and __dirname come from? They look like globals, but they're not. They are the five parameters of the wrapper function, passed in by Node.js:
| Parameter | What it is |
|---|---|
exports | shortcut that points to module.exports |
require | the function you use to import other modules |
module | an object describing the current module (its id, filename, exports, loaded...) |
__filename | absolute path of the current file, e.g. /home/you/app/sum.js |
__dirname | absolute path of the folder it's in, e.g. /home/you/app |
You can prove it. This prints the parameters the wrapper received:
// proof.js
console.log(arguments.length); // 5 (exports, require, module, __filename, __dirname)
console.log(__filename); // full path of proof.js
console.log(this === module.exports); // true: the wrapper is called with this = module.exports// proof.js
console.log(arguments.length); // 5 (exports, require, module, __filename, __dirname)
console.log(__filename); // full path of proof.js
console.log(this === module.exports); // true: the wrapper is called with this = module.exports__dirname is very useful for building paths that work no matter where you start the program from:
path.join(__dirname, "data.json"). In ES Modules these variables don't exist; use import.meta.dirname and import.meta.filename (Node.js 20.11+).
The five steps of require
Every time you call require("./something"), Node.js goes through these steps:
1. Resolve: find the exact file
Node.js turns your string into one absolute path:
- Core module?
fs,path,node:http... are built into Node.js and returned directly. - Starts with
./,../or/? It's a file path. Node tries the exact name, then adds.js,.json,.node; if it's a folder, it uses the folder'spackage.json"main"field orindex.js. - Otherwise (a bare name like
express), Node looks in./node_modules, then../node_modules, and so on up to the root of the disk.
If nothing matches: Error: Cannot find module './something'.
You can ask Node.js what a name resolves to, without loading it:
console.log(require.resolve("./sum")); // /home/you/app/sum.js
console.log(require.resolve("express")); // /home/you/app/node_modules/express/index.jsconsole.log(require.resolve("./sum")); // /home/you/app/sum.js
console.log(require.resolve("express")); // /home/you/app/node_modules/express/index.js2. Load: read the file
Node.js reads the file's contents. What happens next depends on the type: .js files continue to the next steps, .json files are parsed with JSON.parse, and .node files are compiled C++ add-ons.
3. Wrap: put it inside the function
The code is wrapped in the (exports, require, module, __filename, __dirname) function you saw above.
4. Evaluate: run it
Node.js hands the wrapped code to V8, which runs it (Chapter 08: Deep dive into v8 JS Engine covers how V8 executes code). While your file runs, it fills module.exports.
5. Cache: remember it
The finished module is stored in require.cache, keyed by its absolute path. The next require of the same path returns the same module.exports object straight from the cache.
// counter.js
let count = 0;
module.exports = { increment: () => ++count };// counter.js
let count = 0;
module.exports = { increment: () => ++count };// app.js
const a = require("./counter");
const b = require("./counter");
a.increment();
console.log(b.increment()); // 2: a and b are the SAME object
console.log(a === b); // true// app.js
const a = require("./counter");
const b = require("./counter");
a.increment();
console.log(b.increment()); // 2: a and b are the SAME object
console.log(a === b); // trueCaching is why:
- a module's top-level code (like a
console.logor a database connection) runs only once - modules can share state, such as a single configured database client
- requiring the same module from many files costs almost nothing after the first time
Common mistakes with CommonJS
- Thinking
require,__dirnameetc. are globals. They're wrapper parameters, passed in by Node.js. - Expecting a module to run again on a second
require. It won't; it's cached. If you need fresh state each time, export a function that creates it. - Mutating cached exports by accident. Since every file gets the same object, changing
require("./config").port = 1in one file changes it everywhere.
Key takeaways: CommonJS
- Node.js wraps every CommonJS file in
function (exports, require, module, __filename, __dirname) { }. That's why these modules are private. require,module,exports,__filenameand__dirnameare parameters, not globals.requiredoes five steps: resolve → load → wrap → evaluate → cache.- The cache means a module runs once and every importer shares the same
module.exports.
Interview questions: CommonJS
Q1. What is the module wrapper function in Node.js?
Before running a CommonJS module, Node.js wraps its code in (function (exports, require, module, __filename, __dirname) { ... }) and calls it. This gives each file its own private scope (nothing leaks into the global scope) and provides the five module-specific variables as function parameters.
Q2. What are __dirname and __filename?
__filename is the absolute path of the current file; __dirname is the absolute path of the folder containing it. They're parameters of the module wrapper, so they exist in CommonJS but not in ES Modules, where you use import.meta.filename and import.meta.dirname instead.
Q3. What happens when you call require()?
Five steps: (1) resolve the name to an absolute path (core module, file path, or node_modules); (2) if it's already in require.cache, return the cached exports; otherwise (3) load the file, (4) wrap it in the module function, (5) evaluate it with V8 so it fills module.exports, then cache it and return module.exports.
Q4. What is an IIFE and why was it used?
An Immediately Invoked Function Expression, like (function () { ... })(), is a function that runs as soon as it's defined. Before module systems, it was the standard way to create a private scope so variables wouldn't pollute the global namespace. Node's module wrapper uses the same idea.
Q5. How can you force Node.js to load a module again, ignoring the cache?
Delete its entry from the cache: delete require.cache[require.resolve("./config")], then require it again. It's rarely a good idea in application code (other files keep the old copy), but it's used in tests and hot-reload tools.
Q6. What is the value of this at the top level of a CommonJS module?
It's module.exports, initially an empty object {}, because the wrapper function is called with this set to module.exports. In an ES Module, top-level this is undefined.
CommonJS vs ES Modules under the hood
require() (CommonJS) | import (ES Modules) | |
|---|---|---|
| Private scope comes from | the wrapper function | the language itself (module scope) |
| When files are found and read | one at a time, while code runs | all of them first, before any code runs |
| Can it be async? | no: must return synchronously | yes: loading and top-level await can be async |
| Errors like "file not found" | thrown when that line runs | thrown before the program starts |
| Exports | a plain object, module.exports | linked slots: live bindings |
| Cache | require.cache, keyed by file path (you can delete entries) | internal module map, keyed by URL (no public API to clear it) |
Interview question
Q1. How is loading an ES Module different from require()?
require() is an ordinary Node.js function: when that line runs, Node resolves, reads, wraps the file in a function, runs it and caches module.exports, one file at a time and synchronously. V8 sees only plain functions. ES Modules are part of the language: Node resolves and reads every file in the graph first, V8 parses and links them (imports become live bindings to exports), and only then evaluates them, dependencies first, possibly asynchronously. That's why ESM imports are hoisted and static, errors appear before any code runs, top-level await works, and there's no __dirname, require or module.
A tour of Node.js's source code
Node.js is open source: github.com/nodejs/node. You don't need to read it to use Node.js, but knowing the layout helps you understand where things come from.
| Folder | What's inside |
|---|---|
lib/ | the JavaScript side of Node.js: fs.js, http.js, events.js... The module loader lives in lib/internal/modules/cjs/loader.js |
src/ | the C++ side: the glue between JavaScript and the system, like node_file.cc for the file system |
deps/ | the big dependencies Node.js is built on, including v8 (the JavaScript engine) and uv (libuv, async I/O) |
test/, doc/ | tests and the official documentation |
A few things you can find in lib/internal/modules/cjs/loader.js:
Module._load: the function behindrequire. It resolves the path, checksModule._cache(which isrequire.cache), and loads the module if needed.Module._resolveFilename: the resolution step.wrapSafe: wraps your code and compiles it into the wrapper function.
The ES Module loader lives next to it, in lib/internal/modules/esm/: loader.js (resolving and loading), module_job.js (one job per module, which runs the link and evaluate phases) and translators.js (turning .js, .json and CommonJS files into modules). The parsing, linking and evaluating themselves are done by V8, through C++ glue in src/module_wrap.cc.
When you call fs.readFile in JavaScript, the call travels from lib/fs.js into C++ code in src/, which hands the actual work to libuv in deps/uv. That's the topic of Chapter 06: libuv & async IO.
Key takeaways
- Functions create private scope; an IIFE runs a function immediately to use it. CommonJS builds on this, ES Modules get scope from the language.
- ES Modules: construction → linking → evaluation. V8 parses, links and runs; Node.js resolves, reads and caches.
- CommonJS: a wrapper function and five steps: resolve → load → wrap → evaluate → cache.
- Node's source: JavaScript in
lib/, C++ insrc/, V8 and libuv indeps/.
What's next
You've seen that fs.readFile ends up in libuv. In Chapter 06: libuv & async IO you'll meet libuv properly: what it does, why Node.js needs it, and the difference between synchronous and asynchronous code.