| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent 97d1fc0 commit ac6b921
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -30,8 +30,9 @@ The module `circle.js` has exported the functions `area()` and | |||
| 30 | 30 | `circumference()`. To add functions and objects to the root of your module, | |
| 31 | 31 | you can add them to the special `exports` object. | |
| 32 | 32 | ||
| 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`. | ||
| 35 | 36 | ||
| 36 | 37 | If you want the root of your module's export to be a function (such as a | |
| 37 | 38 | 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 | |||
| 425 | 426 | to place your dependencies locally in `node_modules` folders.** They | |
| 426 | 427 | will be loaded faster, and more reliably. | |
| 427 | 428 | ||
| 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 | + | ||
| 428 | 453 | ## The `module` Object | |
| 429 | 454 | ||
| 430 | 455 | <!-- type=var --> | |
| Back | FazBrowse Home | New Git URL |
0 commit comments