Skip to content

Commit

Permalink
doc: mention existence/purpose of module wrapper
Browse files Browse the repository at this point in the history
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 <cjihrig@gmail.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
mtharrison authored and Myles Borins committed Jun 24, 2016
1 parent 97d1fc0 commit ac6b921
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions doc/api/modules.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ The module `circle.js` has exported the functions `area()` and
`circumference()`. To add functions and objects to the root of your module,
you can add them to the special `exports` object.

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

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

## The module wrapper

<!-- type=misc -->

Before a module's code is executed, Node.js will wrap it with a function
wrapper that looks like the following:

```js
(function (exports, require, module, __filename, __dirname) {
// Your module code actually lives in here
});
```

By doing this, Node.js achieves a few things:

- It keeps top-level variables (defined with `var`, `const` or `let`) scoped to
the module rather than the global object.
- It helps to provide some global-looking variables that are actually specific
to the module, such as:
- The `module` and `exports` objects that the implementor can use to export
values from the module.
- The convenience variables `__filename` and `__dirname`, containing the
module's absolute filename and directory path.

## The `module` Object

<!-- type=var -->
Expand Down

0 comments on commit ac6b921

Please sign in to comment.