/usr/share/doc/nodejs-doc/api/modules.html is in nodejs-doc 8.10.0~dfsg-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Modules | Node.js v8.10.0 Documentation</title>
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/sh.css">
<link rel="canonical" href="modules.html">
</head>
<body class="alt apidoc" id="api-section-modules">
<div id="content" class="clearfix">
<div id="column2" class="interior">
<div id="intro" class="interior">
<a href="/" title="Go back to the home page">
Node.js
</a>
</div>
<ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage & Example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-async_hooks" href="async_hooks.html">Async Hooks</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C++ Addons</a></li>
<li><a class="nav-n-api" href="n-api.html">C/C++ Addons - N-API</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-deprecations" href="deprecations.html">Deprecated APIs</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-esm" href="esm.html">ECMAScript Modules</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-http2" href="http2.html">HTTP/2</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-inspector" href="inspector.html">Inspector</a></li>
<li><a class="nav-intl" href="intl.html">Internationalization</a></li>
<li><a class="nav-modules active" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-perf_hooks" href="perf_hooks.html">Performance Hooks</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tracing" href="tracing.html">Tracing</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo & Issue Tracker</a></li>
<li><a class="nav-https-groups-google-com-group-nodejs" href="https://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>
</div>
<div id="column1" data-id="modules" class="interior">
<header>
<h1>Node.js v8.10.0 Documentation</h1>
<div id="gtoc">
<ul>
<li>
<a href="index.html" name="toc">Index</a>
</li>
<li>
<a href="all.html">View on single page</a>
</li>
<li>
<a href="modules.json">View as JSON</a>
</li>
<li class="version-picker">
<a href="#">View another version <span>▼</span></a>
<ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v9.x/api/modules.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/modules.html">8.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/modules.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/modules.html">6.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/modules.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/modules.html">4.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/modules.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/modules.html">0.10.x</a></li></ol>
</li>
</ul>
</div>
<hr>
</header>
<div id="toc">
<h2>Table of Contents</h2>
<ul>
<li><span class="stability_2"><a href="#modules_modules">Modules</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_accessing_the_main_module">Accessing the main module</a></span></li>
<li><span class="stability_undefined"><a href="#modules_addenda_package_manager_tips">Addenda: Package Manager Tips</a></span></li>
<li><span class="stability_undefined"><a href="#modules_all_together">All Together...</a></span></li>
<li><span class="stability_undefined"><a href="#modules_caching">Caching</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_caching_caveats">Module Caching Caveats</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_core_modules">Core Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_cycles">Cycles</a></span></li>
<li><span class="stability_undefined"><a href="#modules_file_modules">File Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_folders_as_modules">Folders as Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_wrapper">The module wrapper</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_scope">The module scope</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_dirname">__dirname</a></span></li>
<li><span class="stability_undefined"><a href="#modules_filename">__filename</a></span></li>
<li><span class="stability_undefined"><a href="#modules_exports">exports</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module">module</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require">require()</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_require_cache">require.cache</a></span></li>
<li><span class="stability_0"><a href="#modules_require_extensions">require.extensions</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require_resolve_request_options">require.resolve(request[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require_resolve_paths_request">require.resolve.paths(request)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_the_module_object">The <code>module</code> Object</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_children">module.children</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_exports">module.exports</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_exports_shortcut">exports shortcut</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_module_filename">module.filename</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_id">module.id</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_loaded">module.loaded</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_parent">module.parent</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_paths">module.paths</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_require_id">module.require(id)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_the_module_object_1">The <code>Module</code> Object</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_builtinmodules">module.builtinModules</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<h1>Modules<span><a class="mark" href="#modules_modules" id="modules_modules">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=module-->
<p>In the Node.js module system, each file is treated as a separate module. For
example, consider a file named <code>foo.js</code>:</p>
<pre><code class="lang-js">const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
</code></pre>
<p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same
directory as <code>foo.js</code>.</p>
<p>Here are the contents of <code>circle.js</code>:</p>
<pre><code class="lang-js">const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r;
</code></pre>
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
<code>circumference()</code>. Functions and objects are added to the root of a module
by specifying additional properties on the special <code>exports</code> object.</p>
<p>Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see <a href="#modules_the_module_wrapper">module wrapper</a>).
In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p>
<p>The <code>module.exports</code> property can be assigned a new value (such as a function
or object).</p>
<p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a Square class:</p>
<pre><code class="lang-js">const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);
</code></pre>
<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
<pre><code class="lang-js">// assigning to exports will not modify module, must use module.exports
module.exports = class Square {
constructor(width) {
this.width = width;
}
area() {
return this.width ** 2;
}
};
</code></pre>
<p>The module system is implemented in the <code>require('module')</code> module.</p>
<h2>Accessing the main module<span><a class="mark" href="#modules_accessing_the_main_module" id="modules_accessing_the_main_module">#</a></span></h2>
<!-- type=misc -->
<p>When a file is run directly from Node.js, <code>require.main</code> is set to its
<code>module</code>. That means that it is possible to determine whether a file has been
run directly by testing <code>require.main === module</code>.</p>
<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
<code>false</code> if run by <code>require('./foo')</code>.</p>
<p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to
<code>__filename</code>), the entry point of the current application can be obtained
by checking <code>require.main.filename</code>.</p>
<h2>Addenda: Package Manager Tips<span><a class="mark" href="#modules_addenda_package_manager_tips" id="modules_addenda_package_manager_tips">#</a></span></h2>
<!-- type=misc -->
<p>The semantics of Node.js's <code>require()</code> function were designed to be general
enough to support a number of reasonable directory structures. Package manager
programs such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to
build native packages from Node.js modules without modification.</p>
<p>Below we give a suggested directory structure that could work:</p>
<p>Let's say that we wanted to have the folder at
<code>/usr/lib/node/<some-package>/<some-version></code> hold the contents of a
specific version of a package.</p>
<p>Packages can depend on one another. In order to install package <code>foo</code>, it
may be necessary to install a specific version of package <code>bar</code>. The <code>bar</code>
package may itself have dependencies, and in some cases, these may even collide
or form cyclic dependencies.</p>
<p>Since Node.js looks up the <code>realpath</code> of any modules it loads (that is,
resolves symlinks), and then looks for their dependencies in the <code>node_modules</code>
folders as described <a href="#modules_loading_from_node_modules_folders">here</a>, this
situation is very simple to resolve with the following architecture:</p>
<ul>
<li><code>/usr/lib/node/foo/1.2.3/</code> - Contents of the <code>foo</code> package, version 1.2.3.</li>
<li><code>/usr/lib/node/bar/4.3.2/</code> - Contents of the <code>bar</code> package that <code>foo</code>
depends on.</li>
<li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code> - Symbolic link to
<code>/usr/lib/node/bar/4.3.2/</code>.</li>
<li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code> - Symbolic links to the packages
that <code>bar</code> depends on.</li>
</ul>
<p>Thus, even if a cycle is encountered, or if there are dependency
conflicts, every module will be able to get a version of its dependency
that it can use.</p>
<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the
version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>.
Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get
the version that is symlinked into
<code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.</p>
<p>Furthermore, to make the module lookup process even more optimal, rather
than putting packages directly in <code>/usr/lib/node</code>, we could put them in
<code>/usr/lib/node_modules/<name>/<version></code>. Then Node.js will not bother
looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p>
<p>In order to make modules available to the Node.js REPL, it might be useful to
also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment
variable. Since the module lookups using <code>node_modules</code> folders are all
relative, and based on the real path of the files making the calls to
<code>require()</code>, the packages themselves can be anywhere.</p>
<h2>All Together...<span><a class="mark" href="#modules_all_together" id="modules_all_together">#</a></span></h2>
<!-- type=misc -->
<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
the <code>require.resolve()</code> function.</p>
<p>Putting together all of the above, here is the high-level algorithm
in pseudocode of what <code>require.resolve()</code> does:</p>
<pre><code class="lang-txt">require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with '/'
a. set Y to be the filesystem root
3. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
4. LOAD_NODE_MODULES(X, dirname(Y))
5. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.json is a file, parse X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
LOAD_INDEX(X)
1. If X/index.js is a file, load X/index.js as JavaScript text. STOP
2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
3. If X/index.node is a file, load X/index.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
d. LOAD_INDEX(M)
2. LOAD_INDEX(X)
LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = []
4. while I >= 0,
a. if PARTS[I] = "node_modules" CONTINUE
b. DIR = path join(PARTS[0 .. I] + "node_modules")
c. DIRS = DIRS + DIR
d. let I = I - 1
5. return DIRS
</code></pre>
<h2>Caching<span><a class="mark" href="#modules_caching" id="modules_caching">#</a></span></h2>
<!--type=misc-->
<p>Modules are cached after the first time they are loaded. This means
(among other things) that every call to <code>require('foo')</code> will get
exactly the same object returned, if it would resolve to the same file.</p>
<p>Multiple calls to <code>require('foo')</code> may not cause the module code to be
executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.</p>
<p>To have a module execute code multiple times, export a function, and call
that function.</p>
<h3>Module Caching Caveats<span><a class="mark" href="#modules_module_caching_caveats" id="modules_module_caching_caveats">#</a></span></h3>
<!--type=misc-->
<p>Modules are cached based on their resolved filename. Since modules may
resolve to a different filename based on the location of the calling
module (loading from <code>node_modules</code> folders), it is not a <em>guarantee</em>
that <code>require('foo')</code> will always return the exact same object, if it
would resolve to different files.</p>
<p>Additionally, on case-insensitive file systems or operating systems, different
resolved filenames can point to the same file, but the cache will still treat
them as different modules and will reload the file multiple times. For example,
<code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects,
irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p>
<h2>Core Modules<span><a class="mark" href="#modules_core_modules" id="modules_core_modules">#</a></span></h2>
<!--type=misc-->
<p>Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The core modules are defined within Node.js's source and are located in the
<code>lib/</code> folder.</p>
<p>Core modules are always preferentially loaded if their identifier is
passed to <code>require()</code>. For instance, <code>require('http')</code> will always
return the built in HTTP module, even if there is a file by that name.</p>
<h2>Cycles<span><a class="mark" href="#modules_cycles" id="modules_cycles">#</a></span></h2>
<!--type=misc-->
<p>When there are circular <code>require()</code> calls, a module might not have finished
executing when it is returned.</p>
<p>Consider this situation:</p>
<p><code>a.js</code>:</p>
<pre><code class="lang-js">console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');
</code></pre>
<p><code>b.js</code>:</p>
<pre><code class="lang-js">console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
console.log('b done');
</code></pre>
<p><code>main.js</code>:</p>
<pre><code class="lang-js">console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
</code></pre>
<p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that
point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite
loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the
<code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is
provided to the <code>a.js</code> module.</p>
<p>By the time <code>main.js</code> has loaded both modules, they're both finished.
The output of this program would thus be:</p>
<pre><code class="lang-txt">$ node main.js
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done=true, b.done=true
</code></pre>
<p>Careful planning is required to allow cyclic module dependencies to work
correctly within an application.</p>
<h2>File Modules<span><a class="mark" href="#modules_file_modules" id="modules_file_modules">#</a></span></h2>
<!--type=misc-->
<p>If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally
<code>.node</code>.</p>
<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are
parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon
modules loaded with <code>dlopen</code>.</p>
<p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For
example, <code>require('/home/marco/foo.js')</code> will load the file at
<code>/home/marco/foo.js</code>.</p>
<p>A required module prefixed with <code>'./'</code> is relative to the file calling
<code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
<code>require('./circle')</code> to find it.</p>
<p>Without a leading '/', './', or '../' to indicate a file, the module must
either be a core module or is loaded from a <code>node_modules</code> folder.</p>
<p>If the given path does not exist, <code>require()</code> will throw an <a href="errors.html#errors_class_error"><code>Error</code></a> with its
<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.</p>
<h2>Folders as Modules<span><a class="mark" href="#modules_folders_as_modules" id="modules_folders_as_modules">#</a></span></h2>
<!--type=misc-->
<p>It is convenient to organize programs and libraries into self-contained
directories, and then provide a single entry point to that library.
There are three ways in which a folder may be passed to <code>require()</code> as
an argument.</p>
<p>The first is to create a <code>package.json</code> file in the root of the folder,
which specifies a <code>main</code> module. An example package.json file might
look like this:</p>
<pre><code class="lang-json">{ "name" : "some-library",
"main" : "./lib/some-library.js" }
</code></pre>
<p>If this was in a folder at <code>./some-library</code>, then
<code>require('./some-library')</code> would attempt to load
<code>./some-library/lib/some-library.js</code>.</p>
<p>This is the extent of Node.js's awareness of package.json files.</p>
<p><em>Note</em>: If the file specified by the <code>"main"</code> entry of <code>package.json</code> is
missing and can not be resolved, Node.js will report the entire module as
missing with the default error:</p>
<pre><code class="lang-txt">Error: Cannot find module 'some-library'
</code></pre>
<p>If there is no package.json file present in the directory, then Node.js
will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
directory. For example, if there was no package.json file in the above
example, then <code>require('./some-library')</code> would attempt to load:</p>
<ul>
<li><code>./some-library/index.js</code></li>
<li><code>./some-library/index.node</code></li>
</ul>
<h2>Loading from <code>node_modules</code> Folders<span><a class="mark" href="#modules_loading_from_node_modules_folders" id="modules_loading_from_node_modules_folders">#</a></span></h2>
<!--type=misc-->
<p>If the module identifier passed to <code>require()</code> is not a
<a href="#modules_core_modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
<code>'./'</code>, then Node.js starts at the parent directory of the current module, and
adds <code>/node_modules</code>, and attempts to load the module from that location. Node
will not append <code>node_modules</code> to a path already ending in <code>node_modules</code>.</p>
<p>If it is not found there, then it moves to the parent directory, and so
on, until the root of the file system is reached.</p>
<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
<code>require('bar.js')</code>, then Node.js would look in the following locations, in
this order:</p>
<ul>
<li><code>/home/ry/projects/node_modules/bar.js</code></li>
<li><code>/home/ry/node_modules/bar.js</code></li>
<li><code>/home/node_modules/bar.js</code></li>
<li><code>/node_modules/bar.js</code></li>
</ul>
<p>This allows programs to localize their dependencies, so that they do not
clash.</p>
<p>It is possible to require specific files or sub modules distributed with a
module by including a path suffix after the module name. For instance
<code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code>
relative to where <code>example-module</code> is located. The suffixed path follows the
same module resolution semantics.</p>
<h2>Loading from the global folders<span><a class="mark" href="#modules_loading_from_the_global_folders" id="modules_loading_from_the_global_folders">#</a></span></h2>
<!-- type=misc -->
<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if they
are not found elsewhere.</p>
<p><em>Note</em>: On Windows, <code>NODE_PATH</code> is delimited by semicolons instead of colons.</p>
<p><code>NODE_PATH</code> was originally created to support loading modules from
varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was frozen.</p>
<p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js
ecosystem has settled on a convention for locating dependent modules.
Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior
when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the <code>NODE_PATH</code> is searched.</p>
<p>Additionally, Node.js will search in the following locations:</p>
<ul>
<li>1: <code>$HOME/.node_modules</code></li>
<li>2: <code>$HOME/.node_libraries</code></li>
<li>3: <code>$PREFIX/lib/node</code></li>
</ul>
<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is Node.js's
configured <code>node_prefix</code>.</p>
<p>These are mostly for historic reasons.</p>
<p><em>Note</em>: It is strongly encouraged to place dependencies in the local
<code>node_modules</code> folder. These will be loaded faster, and more reliably.</p>
<h2>The module wrapper<span><a class="mark" href="#modules_the_module_wrapper" id="modules_the_module_wrapper">#</a></span></h2>
<!-- type=misc -->
<p>Before a module's code is executed, Node.js will wrap it with a function
wrapper that looks like the following:</p>
<pre><code class="lang-js">(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
</code></pre>
<p>By doing this, Node.js achieves a few things:</p>
<ul>
<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code> or <code>let</code>) scoped to
the module rather than the global object.</li>
<li>It helps to provide some global-looking variables that are actually specific
to the module, such as:<ul>
<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export
values from the module.</li>
<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the
module's absolute filename and directory path.</li>
</ul>
</li>
</ul>
<h2>The module scope<span><a class="mark" href="#modules_the_module_scope" id="modules_the_module_scope">#</a></span></h2>
<h3>__dirname<span><a class="mark" href="#modules_dirname" id="modules_dirname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><!-- type=var -->
<ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The directory name of the current module. This is the same as the
<a href="path.html#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_filename"><code>__filename</code></a>.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="lang-js">console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
</code></pre>
<h3>__filename<span><a class="mark" href="#modules_filename" id="modules_filename">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!-- type=var -->
<ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The file name of the current module. This is the resolved absolute path of the
current module file.</p>
<p>For a main program this is not necessarily the same as the file name used in the
command line.</p>
<p>See <a href="#modules_dirname"><code>__dirname</code></a> for the directory name of the current module.</p>
<p>Examples:</p>
<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="lang-js">console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr
</code></pre>
<p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of
<code>a</code> and there is a directory structure of:</p>
<ul>
<li><code>/Users/mjr/app/a.js</code></li>
<li><code>/Users/mjr/app/node_modules/b/b.js</code></li>
</ul>
<p>References to <code>__filename</code> within <code>b.js</code> will return
<code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within
<code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p>
<h3>exports<span><a class="mark" href="#modules_exports" id="modules_exports">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.12</span>
</div><!-- type=var -->
<p>A reference to the <code>module.exports</code> that is shorter to type.
See the section about the <a href="#modules_exports_shortcut">exports shortcut</a> for details on when to use
<code>exports</code> and when to use <code>module.exports</code>.</p>
<h3>module<span><a class="mark" href="#modules_module" id="modules_module">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><!-- type=var -->
<ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>A reference to the current module, see the section about the
<a href="#modules_the_module_object"><code>module</code> object</a>. In particular, <code>module.exports</code> is used for defining what
a module exports and makes available through <code>require()</code>.</p>
<h3>require()<span><a class="mark" href="#modules_require" id="modules_require">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div><!-- type=var -->
<ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>To require modules.</p>
<h4>require.cache<span><a class="mark" href="#modules_require_cache" id="modules_require_cache">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Modules are cached in this object when they are required. By deleting a key
value from this object, the next <code>require</code> will reload the module. Note that
this does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an
Error.</p>
<h4>require.extensions<span><a class="mark" href="#modules_require_extensions" id="modules_require_extensions">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Instruct <code>require</code> on how to handle certain file extensions.</p>
<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p>
<pre><code class="lang-js">require.extensions['.sjs'] = require.extensions['.js'];
</code></pre>
<p><strong>Deprecated</strong> In the past, this list has been used to load
non-JavaScript modules into Node.js by compiling them on-demand.
However, in practice, there are much better ways to do this, such as
loading modules via some other Node.js program, or compiling them to
JavaScript ahead of time.</p>
<p>Since the module system is locked, this feature will probably never go
away. However, it may have subtle bugs and complexities that are best
left untouched.</p>
<p>Note that the number of file system operations that the module system
has to perform in order to resolve a <code>require(...)</code> statement to a
filename scales linearly with the number of registered extensions.</p>
<p>In other words, adding extensions slows down the module loader and
should be discouraged.</p>
<h4>require.resolve(request[, options])<span><a class="mark" href="#modules_require_resolve_request_options" id="modules_require_resolve_request_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.9.0</td>
<td><p>The <code>paths</code> option is now supported.</p>
</td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>request</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path to resolve.</li>
<li><code>options</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>paths</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Paths to resolve module location from. If present, these
paths are used instead of the default resolution paths. Note that each of
these paths is used as a starting point for the module resolution algorithm,
meaning that the <code>node_modules</code> hierarchy is checked from this location.</li>
</ul>
</li>
<li>Returns:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Use the internal <code>require()</code> machinery to look up the location of a module,
but rather than loading the module, just return the resolved filename.</p>
<h4>require.resolve.paths(request)<span><a class="mark" href="#modules_require_resolve_paths_request" id="modules_require_resolve_paths_request">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.9.0</span>
</div><ul>
<li><code>request</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path whose lookup paths are being retrieved.</li>
<li>Returns:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> |
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
<p>Returns an array containing the paths searched during resolution of <code>request</code> or
null if the <code>request</code> string references a core module, for example <code>http</code> or
<code>fs</code>.</p>
<h2>The <code>module</code> Object<span><a class="mark" href="#modules_the_module_object" id="modules_the_module_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><!-- type=var -->
<!-- name=module -->
<ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>In each module, the <code>module</code> free variable is a reference to the object
representing the current module. For convenience, <code>module.exports</code> is
also accessible via the <code>exports</code> module-global. <code>module</code> is not actually
a global but rather local to each module.</p>
<h3>module.children<span><a class="mark" href="#modules_module_children" id="modules_module_children">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>The module objects required by this one.</p>
<h3>module.exports<span><a class="mark" href="#modules_module_exports" id="modules_module_exports">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>module.exports</code> object is created by the Module system. Sometimes this is
not acceptable; many want their module to be an instance of some class. To do
this, assign the desired export object to <code>module.exports</code>. Note that assigning
the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable,
which is probably not what is desired.</p>
<p>For example suppose we were making a module called <code>a.js</code></p>
<pre><code class="lang-js">const EventEmitter = require('events');
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
</code></pre>
<p>Then in another file we could do</p>
<pre><code class="lang-js">const a = require('./a');
a.on('ready', () => {
console.log('module a is ready');
});
</code></pre>
<p>Note that assignment to <code>module.exports</code> must be done immediately. It cannot be
done in any callbacks. This does not work:</p>
<p>x.js:</p>
<pre><code class="lang-js">setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);
</code></pre>
<p>y.js:</p>
<pre><code class="lang-js">const x = require('./x');
console.log(x.a);
</code></pre>
<h4>exports shortcut<span><a class="mark" href="#modules_exports_shortcut" id="modules_exports_shortcut">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>The <code>exports</code> variable is available within a module's file-level scope, and is
assigned the value of <code>module.exports</code> before the module is evaluated.</p>
<p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more
succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a
new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p>
<pre><code class="lang-js">module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module
</code></pre>
<p>When the <code>module.exports</code> property is being completely replaced by a new
object, it is common to also reassign <code>exports</code>, for example:</p>
<!-- eslint-disable func-name-matching -->
<pre><code class="lang-js">module.exports = exports = function Constructor() {
// ... etc.
};
</code></pre>
<p>To illustrate the behavior, imagine this hypothetical implementation of
<code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p>
<pre><code class="lang-js">function require(/* ... */) {
const module = { exports: {} };
((module, exports) => {
// Module code here. In this example, define a function.
function someFunc() {}
exports = someFunc;
// At this point, exports is no longer a shortcut to module.exports, and
// this module will still export an empty default object.
module.exports = someFunc;
// At this point, the module will now export someFunc, instead of the
// default object.
})(module, module.exports);
return module.exports;
}
</code></pre>
<h3>module.filename<span><a class="mark" href="#modules_module_filename" id="modules_module_filename">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The fully resolved filename to the module.</p>
<h3>module.id<span><a class="mark" href="#modules_module_id" id="modules_module_id">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The identifier for the module. Typically this is the fully resolved
filename.</p>
<h3>module.loaded<span><a class="mark" href="#modules_module_loaded" id="modules_module_loaded">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Whether or not the module is done loading, or is in the process of
loading.</p>
<h3>module.parent<span><a class="mark" href="#modules_module_parent" id="modules_module_parent">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Module object</li>
</ul>
<p>The module that first required this one.</p>
<h3>module.paths<span><a class="mark" href="#modules_module_paths" id="modules_module_paths">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The search paths for the module.</p>
<h3>module.require(id)<span><a class="mark" href="#modules_module_require_id" id="modules_module_require_id">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div><ul>
<li><code>id</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <code>module.exports</code> from the resolved module</li>
</ul>
<p>The <code>module.require</code> method provides a way to load a module as if
<code>require()</code> was called from the original module.</p>
<p><em>Note</em>: In order to do this, it is necessary to get a reference to the
<code>module</code> object. Since <code>require()</code> returns the <code>module.exports</code>, and the
<code>module</code> is typically <em>only</em> available within a specific module's code, it must
be explicitly exported in order to be used.</p>
<h2>The <code>Module</code> Object<span><a class="mark" href="#modules_the_module_object_1" id="modules_the_module_object_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.7</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Provides general utility methods when interacting with instances of
<code>Module</code> -- the <code>module</code> variable often seen in file modules. Accessed
via <code>require('module')</code>.</p>
<h3>module.builtinModules<span><a class="mark" href="#modules_module_builtinmodules" id="modules_module_builtinmodules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.10.0</span>
</div><ul>
<li>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>A list of the names of all modules provided by Node.js. Can be used to verify
if a module is maintained by a third-party module or not.</p>
</div>
</div>
</div>
<script src="assets/sh_main.js"></script>
<script src="assets/sh_javascript.min.js"></script>
<script>highlight(undefined, undefined, 'pre');</script>
<!-- __TRACKING__ -->
</body>
</html>
|