In Node.js CommonJS, what is the module wrapper function, and how does it give each file its own exports, require, module, __filename and __dirname?
answer
- source wrapped before it runs
- five parameters, not globals
- this equals module.exports
- __dirname differs from process.cwd()
basics
~20 sNode wraps each CommonJS file's source in a function taking exports, require, module, __filename and __dirname, then calls it once with this set to module.exports, so those names are per-file arguments and top-level variables stay module-local.
solid answer
~40 sNode's CommonJS loader compiles a file as the body of `function (exports, require, module, __filename, __dirname) { ... }` and calls it once with `this` set to `module.exports`. That explains several behaviours: top-level `const` and `let` are function locals, not properties of `globalThis`; `require` is a per-module function that resolves relative specifiers from that file's location; `__filename` is the file's absolute path with symlinks resolved and `__dirname` its directory, which is not the same as `process.cwd()`; and `exports` is just a parameter that starts out pointing at `module.exports`, while `require` returns `module.exports`. Files loaded as ES modules are not wrapped, so none of the five names exist there.
code
javascript · 10 lines// app/lib/paths.js, started from the repository root with: node app/server.js
const path = require('node:path');
console.log(this === module.exports); // true: the wrapper's this
console.log(typeof globalThis.templatesDir); // undefined: top-level const stays local
console.log(__dirname); // /repo/app/lib
console.log(process.cwd()); // /repo
const templatesDir = path.join(__dirname, 'templates');
module.exports = { templatesDir };go deeper
Recall that Node wraps each CommonJS file in a function whose five parameters are exports, require, module, __filename and __dirname.
Explain the consequences: module-scoped top-level variables, this equal to module.exports, require resolving relative to the file, and __dirname versus process.cwd().
Diagnose the bugs the wrapper explains, such as asset paths that break when the service starts from another directory or exports assigned too late to reach callers.
Treat wrapper-provided names as a CommonJS dependency when planning a module-format change, since every __dirname and require call needs an explicit replacement.
## The function Node puts around every CommonJS file Node does not run a CommonJS file's source as-is. Before executing it, the CommonJS loader places the source inside a function and calls that function once. The Node documentation shows the shape: ```js (function (exports, require, module, __filename, __dirname) { // the file's own code goes here }); ``` Node then calls this function with `this` set to the module's `exports` object and passes five arguments. Every name that looks like a global in a CommonJS file but is really per-file comes from this call. ## What each parameter is | Parameter | What Node passes | Typical use | |---|---|---| | `exports` | The initial `module.exports` object | Shortcut for adding properties: `exports.parse = ...` | | `require` | A function bound to this module | Loading other modules relative to this file | | `module` | The `Module` object for this file | `module.exports`, `module.id`, `module.children`, `require.main === module` checks | | `__filename` | Absolute path of this file, symlinks resolved | Logging, locating sibling files | | `__dirname` | Directory of `__filename` | Building paths to assets next to the file | ## Consequences you can observe The wrapper is small, but several everyday behaviours follow from it: - **Top-level declarations are module-scoped.** `const port = 3000` at the top of one file and `const port = 8080` in another never collide, and neither becomes a property of `globalThis`, because each is a local of its own wrapper function. - **`this` at the top level is `module.exports`.** `console.log(this === module.exports)` prints `true` in a CommonJS file, unlike a browser script where top-level `this` is the global object. - **`require` is per-module.** Relative specifiers such as `./db` are resolved from the requiring file's location, which is why the same string means different files in different folders. - **`__dirname` is not the working directory.** `__dirname` is where the file lives; `process.cwd()` is where the process was started. A server launched from the repository root as `node app/server.js` has a working directory of the root, while `__dirname` inside `app/lib/db.js` is `.../app/lib`. Relative paths passed to `node:fs` resolve against `process.cwd()`, so asset paths should be built from `__dirname` with `path.join`. - **`exports` is only a parameter.** It starts out pointing at `module.exports`; adding properties to it adds them to `module.exports`. Assigning a new value to `exports` rebinds the local name and leaves `module.exports` untouched, and `require` always returns `module.exports`. ## Timing: the wrapper runs once, synchronously The wrapper function is called once, on the first `require` of that resolved file, and `require` returns `module.exports` as soon as the call finishes. Two practical rules follow: 1. **Assign `module.exports` during that synchronous run.** The Node docs are explicit that replacing `module.exports` inside a callback, such as a `setTimeout`, does not work: the caller already received the original object. 2. **Export something that can change later if you need deferred readiness.** Export an `EventEmitter` or an object whose properties you fill in later, so callers keep a reference that stays valid. ## What the wrapper does not give you The wrapper exists only for CommonJS. Files Node loads as ES modules are not wrapped, so `exports`, `require`, `module`, `__filename` and `__dirname` are simply not defined there, and replacing them is a separate subject (the material on ES modules in Node covers `import.meta.dirname` and `createRequire`). Two more limits are worth knowing: - **The wrapper is not a sandbox.** Code inside it still shares `globalThis`, `process` and the same event loop with every other module; writing `globalThis.x = 1` is visible everywhere. - **The parameters are not magic.** Because they are plain arguments, they can be shadowed or reassigned like any variable, which is exactly how the `exports = {...}` mistake happens. ## Checking it yourself A quick way to see the wrapper in action: 1. Create `t.js` containing `const port = 1; console.log(this === module.exports, typeof globalThis.port);` and run `node t.js`: it prints `true undefined`, because `this` is the exports object and `port` never reaches `globalThis`. 2. Log `__dirname` and `process.cwd()` from a file in a subfolder and start Node from a different directory to see them differ. 3. Throw an error at the top of a module and read the stack trace: the frame for your file appears as `Object.<anonymous>`, the anonymous wrapper function, called from `Module._compile`.
- In Node.js, why does replacing module.exports inside a setTimeout callback not work?The wrapper runs synchronously and `require` returns `module.exports` the moment it finishes. A caller that required the file already holds the original object; reassigning `module.exports` later points the module at a new object nobody has. To signal readiness later, export something that stays the same reference, such as an `EventEmitter` that emits `'ready'`, and fill it in over time.
- In a Node.js CommonJS file, how can code tell whether it was run directly with node or required by another file?Compare `require.main === module`. `require.main` is the `Module` for the entry script, and `module` is the current file's own wrapper argument, so they are the same object only when the file is the entry point. `require.main` is `undefined` when the entry point is not a CommonJS module.
- require, module and __dirname are true globals available in every Node file
- __dirname is the directory the node command was started from
- Top-level const in a CommonJS file becomes a property of globalThis
- The wrapper isolates each module in its own sandboxed global scope
- ES modules in Node also receive __filename and __dirname from the wrapper