Skip to content

Commit ac6b921

Browse files
mtharrisonMyles Borins
authored and
Myles Borins
committed
doc: mention existence/purpose of module wrapper
Included a block in the modules.md file to explain the existence and purpose of the module wrapper. PR-URL: #6433 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 97d1fc0 commit ac6b921

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

doc/api/modules.markdown

+27-2
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ The module `circle.js` has exported the functions `area()` and
3030
`circumference()`. To add functions and objects to the root of your module,
3131
you can add them to the special `exports` object.
3232

33-
Variables local to the module will be private, as though the module was wrapped
34-
in a function. In this example the variable `PI` is private to `circle.js`.
33+
Variables local to the module will be private, because the module is wrapped
34+
in a function by Node.js (see [module wrapper](#modules_the_module_wrapper)).
35+
In this example, the variable `PI` is private to `circle.js`.
3536

3637
If you want the root of your module's export to be a function (such as a
3738
constructor) or if you want to export a complete object in one assignment
@@ -425,6 +426,30 @@ These are mostly for historic reasons. **You are highly encouraged
425426
to place your dependencies locally in `node_modules` folders.** They
426427
will be loaded faster, and more reliably.
427428

429+
## The module wrapper
430+
431+
<!-- type=misc -->
432+
433+
Before a module's code is executed, Node.js will wrap it with a function
434+
wrapper that looks like the following:
435+
436+
```js
437+
(function (exports, require, module, __filename, __dirname) {
438+
// Your module code actually lives in here
439+
});
440+
```
441+
442+
By doing this, Node.js achieves a few things:
443+
444+
- It keeps top-level variables (defined with `var`, `const` or `let`) scoped to
445+
the module rather than the global object.
446+
- It helps to provide some global-looking variables that are actually specific
447+
to the module, such as:
448+
- The `module` and `exports` objects that the implementor can use to export
449+
values from the module.
450+
- The convenience variables `__filename` and `__dirname`, containing the
451+
module's absolute filename and directory path.
452+
428453
## The `module` Object
429454

430455
<!-- type=var -->

0 commit comments

Comments
 (0)