1# Modules: CommonJS modules 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!--name=module--> 8 9In the Node.js module system, each file is treated as a separate module. For 10example, consider a file named `foo.js`: 11 12```js 13const circle = require('./circle.js'); 14console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); 15``` 16 17On the first line, `foo.js` loads the module `circle.js` that is in the same 18directory as `foo.js`. 19 20Here are the contents of `circle.js`: 21 22```js 23const { PI } = Math; 24 25exports.area = (r) => PI * r ** 2; 26 27exports.circumference = (r) => 2 * PI * r; 28``` 29 30The module `circle.js` has exported the functions `area()` and 31`circumference()`. Functions and objects are added to the root of a module 32by specifying additional properties on the special `exports` object. 33 34Variables local to the module will be private, because the module is wrapped 35in a function by Node.js (see [module wrapper](#modules_the_module_wrapper)). 36In this example, the variable `PI` is private to `circle.js`. 37 38The `module.exports` property can be assigned a new value (such as a function 39or object). 40 41Below, `bar.js` makes use of the `square` module, which exports a Square class: 42 43```js 44const Square = require('./square.js'); 45const mySquare = new Square(2); 46console.log(`The area of mySquare is ${mySquare.area()}`); 47``` 48 49The `square` module is defined in `square.js`: 50 51```js 52// Assigning to exports will not modify module, must use module.exports 53module.exports = class Square { 54 constructor(width) { 55 this.width = width; 56 } 57 58 area() { 59 return this.width ** 2; 60 } 61}; 62``` 63 64The module system is implemented in the `require('module')` module. 65 66## Accessing the main module 67 68<!-- type=misc --> 69 70When a file is run directly from Node.js, `require.main` is set to its 71`module`. That means that it is possible to determine whether a file has been 72run directly by testing `require.main === module`. 73 74For a file `foo.js`, this will be `true` if run via `node foo.js`, but 75`false` if run by `require('./foo')`. 76 77Because `module` provides a `filename` property (normally equivalent to 78`__filename`), the entry point of the current application can be obtained 79by checking `require.main.filename`. 80 81## Addenda: Package manager tips 82 83<!-- type=misc --> 84 85The semantics of the Node.js `require()` function were designed to be general 86enough to support reasonable directory structures. Package manager programs 87such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to build 88native packages from Node.js modules without modification. 89 90Below we give a suggested directory structure that could work: 91 92Let's say that we wanted to have the folder at 93`/usr/lib/node/<some-package>/<some-version>` hold the contents of a 94specific version of a package. 95 96Packages can depend on one another. In order to install package `foo`, it 97may be necessary to install a specific version of package `bar`. The `bar` 98package may itself have dependencies, and in some cases, these may even collide 99or form cyclic dependencies. 100 101Because Node.js looks up the `realpath` of any modules it loads (that is, it 102resolves symlinks) and then [looks for their dependencies in `node_modules` folders](#modules_loading_from_node_modules_folders), 103this situation can be resolved with the following architecture: 104 105* `/usr/lib/node/foo/1.2.3/`: Contents of the `foo` package, version 1.2.3. 106* `/usr/lib/node/bar/4.3.2/`: Contents of the `bar` package that `foo` depends 107 on. 108* `/usr/lib/node/foo/1.2.3/node_modules/bar`: Symbolic link to 109 `/usr/lib/node/bar/4.3.2/`. 110* `/usr/lib/node/bar/4.3.2/node_modules/*`: Symbolic links to the packages that 111 `bar` depends on. 112 113Thus, even if a cycle is encountered, or if there are dependency 114conflicts, every module will be able to get a version of its dependency 115that it can use. 116 117When the code in the `foo` package does `require('bar')`, it will get the 118version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`. 119Then, when the code in the `bar` package calls `require('quux')`, it'll get 120the version that is symlinked into 121`/usr/lib/node/bar/4.3.2/node_modules/quux`. 122 123Furthermore, to make the module lookup process even more optimal, rather 124than putting packages directly in `/usr/lib/node`, we could put them in 125`/usr/lib/node_modules/<name>/<version>`. Then Node.js will not bother 126looking for missing dependencies in `/usr/node_modules` or `/node_modules`. 127 128In order to make modules available to the Node.js REPL, it might be useful to 129also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment 130variable. Since the module lookups using `node_modules` folders are all 131relative, and based on the real path of the files making the calls to 132`require()`, the packages themselves can be anywhere. 133 134## Addenda: The `.mjs` extension 135 136It is not possible to `require()` files that have the `.mjs` extension. 137Attempting to do so will throw [an error][]. The `.mjs` extension is 138reserved for [ECMAScript Modules][] which cannot be loaded via `require()`. 139See [ECMAScript Modules][] for more details. 140 141## All together... 142 143<!-- type=misc --> 144 145To get the exact filename that will be loaded when `require()` is called, use 146the `require.resolve()` function. 147 148Putting together all of the above, here is the high-level algorithm 149in pseudocode of what `require()` does: 150 151```text 152require(X) from module at path Y 1531. If X is a core module, 154 a. return the core module 155 b. STOP 1562. If X begins with '/' 157 a. set Y to be the filesystem root 1583. If X begins with './' or '/' or '../' 159 a. LOAD_AS_FILE(Y + X) 160 b. LOAD_AS_DIRECTORY(Y + X) 161 c. THROW "not found" 1624. If X begins with '#' 163 a. LOAD_PACKAGE_IMPORTS(X, dirname(Y)) 1645. LOAD_PACKAGE_SELF(X, dirname(Y)) 1656. LOAD_NODE_MODULES(X, dirname(Y)) 1667. THROW "not found" 167 168LOAD_AS_FILE(X) 1691. If X is a file, load X as its file extension format. STOP 1702. If X.js is a file, load X.js as JavaScript text. STOP 1713. If X.json is a file, parse X.json to a JavaScript Object. STOP 1724. If X.node is a file, load X.node as binary addon. STOP 173 174LOAD_INDEX(X) 1751. If X/index.js is a file, load X/index.js as JavaScript text. STOP 1762. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 1773. If X/index.node is a file, load X/index.node as binary addon. STOP 178 179LOAD_AS_DIRECTORY(X) 1801. If X/package.json is a file, 181 a. Parse X/package.json, and look for "main" field. 182 b. If "main" is a falsy value, GOTO 2. 183 c. let M = X + (json main field) 184 d. LOAD_AS_FILE(M) 185 e. LOAD_INDEX(M) 186 f. LOAD_INDEX(X) DEPRECATED 187 g. THROW "not found" 1882. LOAD_INDEX(X) 189 190LOAD_NODE_MODULES(X, START) 1911. let DIRS = NODE_MODULES_PATHS(START) 1922. for each DIR in DIRS: 193 a. LOAD_PACKAGE_EXPORTS(X, DIR) 194 b. LOAD_AS_FILE(DIR/X) 195 c. LOAD_AS_DIRECTORY(DIR/X) 196 197NODE_MODULES_PATHS(START) 1981. let PARTS = path split(START) 1992. let I = count of PARTS - 1 2003. let DIRS = [GLOBAL_FOLDERS] 2014. while I >= 0, 202 a. if PARTS[I] = "node_modules" CONTINUE 203 b. DIR = path join(PARTS[0 .. I] + "node_modules") 204 c. DIRS = DIRS + DIR 205 d. let I = I - 1 2065. return DIRS 207 208LOAD_PACKAGE_IMPORTS(X, DIR) 2091. Find the closest package scope SCOPE to DIR. 2102. If no scope was found, return. 2113. If the SCOPE/package.json "imports" is null or undefined, return. 2124. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), 213 ["node", "require"]) defined in the ESM resolver. 2145. RESOLVE_ESM_MATCH(MATCH). 215 216LOAD_PACKAGE_EXPORTS(X, DIR) 2171. Try to interpret X as a combination of NAME and SUBPATH where the name 218 may have a @scope/ prefix and the subpath begins with a slash (`/`). 2192. If X does not match this pattern or DIR/NAME/package.json is not a file, 220 return. 2213. Parse DIR/NAME/package.json, and look for "exports" field. 2224. If "exports" is null or undefined, return. 2235. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH, 224 `package.json` "exports", ["node", "require"]) defined in the ESM resolver. 2256. RESOLVE_ESM_MATCH(MATCH) 226 227LOAD_PACKAGE_SELF(X, DIR) 2281. Find the closest package scope SCOPE to DIR. 2292. If no scope was found, return. 2303. If the SCOPE/package.json "exports" is null or undefined, return. 2314. If the SCOPE/package.json "name" is not the first segment of X, return. 2325. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE), 233 "." + X.slice("name".length), `package.json` "exports", ["node", "require"]) 234 defined in the ESM resolver. 2356. RESOLVE_ESM_MATCH(MATCH) 236 237RESOLVE_ESM_MATCH(MATCH) 2381. let { RESOLVED, EXACT } = MATCH 2392. let RESOLVED_PATH = fileURLToPath(RESOLVED) 2403. If EXACT is true, 241 a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension 242 format. STOP 2434. Otherwise, if EXACT is false, 244 a. LOAD_AS_FILE(RESOLVED_PATH) 245 b. LOAD_AS_DIRECTORY(RESOLVED_PATH) 2465. THROW "not found" 247``` 248 249## Caching 250 251<!--type=misc--> 252 253Modules are cached after the first time they are loaded. This means (among other 254things) that every call to `require('foo')` will get exactly the same object 255returned, if it would resolve to the same file. 256 257Provided `require.cache` is not modified, multiple calls to `require('foo')` 258will not cause the module code to be executed multiple times. This is an 259important feature. With it, "partially done" objects can be returned, thus 260allowing transitive dependencies to be loaded even when they would cause cycles. 261 262To have a module execute code multiple times, export a function, and call that 263function. 264 265### Module caching caveats 266 267<!--type=misc--> 268 269Modules are cached based on their resolved filename. Since modules may resolve 270to a different filename based on the location of the calling module (loading 271from `node_modules` folders), it is not a *guarantee* that `require('foo')` will 272always return the exact same object, if it would resolve to different files. 273 274Additionally, on case-insensitive file systems or operating systems, different 275resolved filenames can point to the same file, but the cache will still treat 276them as different modules and will reload the file multiple times. For example, 277`require('./foo')` and `require('./FOO')` return two different objects, 278irrespective of whether or not `./foo` and `./FOO` are the same file. 279 280## Core modules 281 282<!--type=misc--> 283 284Node.js has several modules compiled into the binary. These modules are 285described in greater detail elsewhere in this documentation. 286 287The core modules are defined within the Node.js source and are located in the 288`lib/` folder. 289 290Core modules are always preferentially loaded if their identifier is 291passed to `require()`. For instance, `require('http')` will always 292return the built in HTTP module, even if there is a file by that name. 293 294## Cycles 295 296<!--type=misc--> 297 298When there are circular `require()` calls, a module might not have finished 299executing when it is returned. 300 301Consider this situation: 302 303`a.js`: 304 305```js 306console.log('a starting'); 307exports.done = false; 308const b = require('./b.js'); 309console.log('in a, b.done = %j', b.done); 310exports.done = true; 311console.log('a done'); 312``` 313 314`b.js`: 315 316```js 317console.log('b starting'); 318exports.done = false; 319const a = require('./a.js'); 320console.log('in b, a.done = %j', a.done); 321exports.done = true; 322console.log('b done'); 323``` 324 325`main.js`: 326 327```js 328console.log('main starting'); 329const a = require('./a.js'); 330const b = require('./b.js'); 331console.log('in main, a.done = %j, b.done = %j', a.done, b.done); 332``` 333 334When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that 335point, `b.js` tries to load `a.js`. In order to prevent an infinite 336loop, an **unfinished copy** of the `a.js` exports object is returned to the 337`b.js` module. `b.js` then finishes loading, and its `exports` object is 338provided to the `a.js` module. 339 340By the time `main.js` has loaded both modules, they're both finished. 341The output of this program would thus be: 342 343```console 344$ node main.js 345main starting 346a starting 347b starting 348in b, a.done = false 349b done 350in a, b.done = true 351a done 352in main, a.done = true, b.done = true 353``` 354 355Careful planning is required to allow cyclic module dependencies to work 356correctly within an application. 357 358## File modules 359 360<!--type=misc--> 361 362If the exact filename is not found, then Node.js will attempt to load the 363required filename with the added extensions: `.js`, `.json`, and finally 364`.node`. 365 366`.js` files are interpreted as JavaScript text files, and `.json` files are 367parsed as JSON text files. `.node` files are interpreted as compiled addon 368modules loaded with `process.dlopen()`. 369 370A required module prefixed with `'/'` is an absolute path to the file. For 371example, `require('/home/marco/foo.js')` will load the file at 372`/home/marco/foo.js`. 373 374A required module prefixed with `'./'` is relative to the file calling 375`require()`. That is, `circle.js` must be in the same directory as `foo.js` for 376`require('./circle')` to find it. 377 378Without a leading `'/'`, `'./'`, or `'../'` to indicate a file, the module must 379either be a core module or is loaded from a `node_modules` folder. 380 381If the given path does not exist, `require()` will throw an [`Error`][] with its 382`code` property set to `'MODULE_NOT_FOUND'`. 383 384## Folders as modules 385 386<!--type=misc--> 387 388It is convenient to organize programs and libraries into self-contained 389directories, and then provide a single entry point to those directories. 390There are three ways in which a folder may be passed to `require()` as 391an argument. 392 393The first is to create a [`package.json`][] file in the root of the folder, 394which specifies a `main` module. An example [`package.json`][] file might 395look like this: 396 397```json 398{ "name" : "some-library", 399 "main" : "./lib/some-library.js" } 400``` 401 402If this was in a folder at `./some-library`, then 403`require('./some-library')` would attempt to load 404`./some-library/lib/some-library.js`. 405 406This is the extent of the awareness of `package.json` files within Node.js. 407 408If there is no [`package.json`][] file present in the directory, or if the 409[`"main"`][] entry is missing or cannot be resolved, then Node.js 410will attempt to load an `index.js` or `index.node` file out of that 411directory. For example, if there was no [`package.json`][] file in the previous 412example, then `require('./some-library')` would attempt to load: 413 414* `./some-library/index.js` 415* `./some-library/index.node` 416 417If these attempts fail, then Node.js will report the entire module as missing 418with the default error: 419 420```console 421Error: Cannot find module 'some-library' 422``` 423 424## Loading from `node_modules` folders 425 426<!--type=misc--> 427 428If the module identifier passed to `require()` is not a 429[core](#modules_core_modules) module, and does not begin with `'/'`, `'../'`, or 430`'./'`, then Node.js starts at the parent directory of the current module, and 431adds `/node_modules`, and attempts to load the module from that location. 432Node.js will not append `node_modules` to a path already ending in 433`node_modules`. 434 435If it is not found there, then it moves to the parent directory, and so 436on, until the root of the file system is reached. 437 438For example, if the file at `'/home/ry/projects/foo.js'` called 439`require('bar.js')`, then Node.js would look in the following locations, in 440this order: 441 442* `/home/ry/projects/node_modules/bar.js` 443* `/home/ry/node_modules/bar.js` 444* `/home/node_modules/bar.js` 445* `/node_modules/bar.js` 446 447This allows programs to localize their dependencies, so that they do not 448clash. 449 450It is possible to require specific files or sub modules distributed with a 451module by including a path suffix after the module name. For instance 452`require('example-module/path/to/file')` would resolve `path/to/file` 453relative to where `example-module` is located. The suffixed path follows the 454same module resolution semantics. 455 456## Loading from the global folders 457 458<!-- type=misc --> 459 460If the `NODE_PATH` environment variable is set to a colon-delimited list 461of absolute paths, then Node.js will search those paths for modules if they 462are not found elsewhere. 463 464On Windows, `NODE_PATH` is delimited by semicolons (`;`) instead of colons. 465 466`NODE_PATH` was originally created to support loading modules from 467varying paths before the current [module resolution][] algorithm was defined. 468 469`NODE_PATH` is still supported, but is less necessary now that the Node.js 470ecosystem has settled on a convention for locating dependent modules. 471Sometimes deployments that rely on `NODE_PATH` show surprising behavior 472when people are unaware that `NODE_PATH` must be set. Sometimes a 473module's dependencies change, causing a different version (or even a 474different module) to be loaded as the `NODE_PATH` is searched. 475 476Additionally, Node.js will search in the following list of GLOBAL_FOLDERS: 477 478* 1: `$HOME/.node_modules` 479* 2: `$HOME/.node_libraries` 480* 3: `$PREFIX/lib/node` 481 482Where `$HOME` is the user's home directory, and `$PREFIX` is the Node.js 483configured `node_prefix`. 484 485These are mostly for historic reasons. 486 487It is strongly encouraged to place dependencies in the local `node_modules` 488folder. These will be loaded faster, and more reliably. 489 490## The module wrapper 491 492<!-- type=misc --> 493 494Before a module's code is executed, Node.js will wrap it with a function 495wrapper that looks like the following: 496 497```js 498(function(exports, require, module, __filename, __dirname) { 499// Module code actually lives in here 500}); 501``` 502 503By doing this, Node.js achieves a few things: 504 505* It keeps top-level variables (defined with `var`, `const` or `let`) scoped to 506the module rather than the global object. 507* It helps to provide some global-looking variables that are actually specific 508 to the module, such as: 509 * The `module` and `exports` objects that the implementor can use to export 510 values from the module. 511 * The convenience variables `__filename` and `__dirname`, containing the 512 module's absolute filename and directory path. 513 514## The module scope 515 516### `__dirname` 517<!-- YAML 518added: v0.1.27 519--> 520 521<!-- type=var --> 522 523* {string} 524 525The directory name of the current module. This is the same as the 526[`path.dirname()`][] of the [`__filename`][]. 527 528Example: running `node example.js` from `/Users/mjr` 529 530```js 531console.log(__dirname); 532// Prints: /Users/mjr 533console.log(path.dirname(__filename)); 534// Prints: /Users/mjr 535``` 536 537### `__filename` 538<!-- YAML 539added: v0.0.1 540--> 541 542<!-- type=var --> 543 544* {string} 545 546The file name of the current module. This is the current module file's absolute 547path with symlinks resolved. 548 549For a main program this is not necessarily the same as the file name used in the 550command line. 551 552See [`__dirname`][] for the directory name of the current module. 553 554Examples: 555 556Running `node example.js` from `/Users/mjr` 557 558```js 559console.log(__filename); 560// Prints: /Users/mjr/example.js 561console.log(__dirname); 562// Prints: /Users/mjr 563``` 564 565Given two modules: `a` and `b`, where `b` is a dependency of 566`a` and there is a directory structure of: 567 568* `/Users/mjr/app/a.js` 569* `/Users/mjr/app/node_modules/b/b.js` 570 571References to `__filename` within `b.js` will return 572`/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within 573`a.js` will return `/Users/mjr/app/a.js`. 574 575### `exports` 576<!-- YAML 577added: v0.1.12 578--> 579 580<!-- type=var --> 581 582* {Object} 583 584A reference to the `module.exports` that is shorter to type. 585See the section about the [exports shortcut][] for details on when to use 586`exports` and when to use `module.exports`. 587 588### `module` 589<!-- YAML 590added: v0.1.16 591--> 592 593<!-- type=var --> 594 595* {module} 596 597A reference to the current module, see the section about the 598[`module` object][]. In particular, `module.exports` is used for defining what 599a module exports and makes available through `require()`. 600 601### `require(id)` 602<!-- YAML 603added: v0.1.13 604--> 605 606<!-- type=var --> 607 608* `id` {string} module name or path 609* Returns: {any} exported module content 610 611Used to import modules, `JSON`, and local files. Modules can be imported 612from `node_modules`. Local modules and JSON files can be imported using 613a relative path (e.g. `./`, `./foo`, `./bar/baz`, `../foo`) that will be 614resolved against the directory named by [`__dirname`][] (if defined) or 615the current working directory. The relative paths of POSIX style are resolved 616in an OS independent fashion, meaning that the examples above will work on 617Windows in the same way they would on Unix systems. 618 619```js 620// Importing a local module with a path relative to the `__dirname` or current 621// working directory. (On Windows, this would resolve to .\path\myLocalModule.) 622const myLocalModule = require('./path/myLocalModule'); 623 624// Importing a JSON file: 625const jsonData = require('./path/filename.json'); 626 627// Importing a module from node_modules or Node.js built-in module: 628const crypto = require('crypto'); 629``` 630 631#### `require.cache` 632<!-- YAML 633added: v0.3.0 634--> 635 636* {Object} 637 638Modules are cached in this object when they are required. By deleting a key 639value from this object, the next `require` will reload the module. 640This does not apply to [native addons][], for which reloading will result in an 641error. 642 643Adding or replacing entries is also possible. This cache is checked before 644native modules and if a name matching a native module is added to the cache, 645no require call is 646going to receive the native module anymore. Use with care! 647 648#### `require.extensions` 649<!-- YAML 650added: v0.3.0 651deprecated: v0.10.6 652--> 653 654> Stability: 0 - Deprecated 655 656* {Object} 657 658Instruct `require` on how to handle certain file extensions. 659 660Process files with the extension `.sjs` as `.js`: 661 662```js 663require.extensions['.sjs'] = require.extensions['.js']; 664``` 665 666**Deprecated.** In the past, this list has been used to load non-JavaScript 667modules into Node.js by compiling them on-demand. However, in practice, there 668are much better ways to do this, such as loading modules via some other Node.js 669program, or compiling them to JavaScript ahead of time. 670 671Avoid using `require.extensions`. Use could cause subtle bugs and resolving the 672extensions gets slower with each registered extension. 673 674#### `require.main` 675<!-- YAML 676added: v0.1.17 677--> 678 679* {module} 680 681The `Module` object representing the entry script loaded when the Node.js 682process launched. 683See ["Accessing the main module"](#modules_accessing_the_main_module). 684 685In `entry.js` script: 686 687```js 688console.log(require.main); 689``` 690 691```bash 692node entry.js 693``` 694 695<!-- eslint-skip --> 696```js 697Module { 698 id: '.', 699 path: '/absolute/path/to', 700 exports: {}, 701 parent: null, 702 filename: '/absolute/path/to/entry.js', 703 loaded: false, 704 children: [], 705 paths: 706 [ '/absolute/path/to/node_modules', 707 '/absolute/path/node_modules', 708 '/absolute/node_modules', 709 '/node_modules' ] } 710``` 711 712#### `require.resolve(request[, options])` 713<!-- YAML 714added: v0.3.0 715changes: 716 - version: v8.9.0 717 pr-url: https://github.com/nodejs/node/pull/16397 718 description: The `paths` option is now supported. 719--> 720 721* `request` {string} The module path to resolve. 722* `options` {Object} 723 * `paths` {string[]} Paths to resolve module location from. If present, these 724 paths are used instead of the default resolution paths, with the exception 725 of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always 726 included. Each of these paths is used as a starting point for 727 the module resolution algorithm, meaning that the `node_modules` hierarchy 728 is checked from this location. 729* Returns: {string} 730 731Use the internal `require()` machinery to look up the location of a module, 732but rather than loading the module, just return the resolved filename. 733 734If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. 735 736##### `require.resolve.paths(request)` 737<!-- YAML 738added: v8.9.0 739--> 740 741* `request` {string} The module path whose lookup paths are being retrieved. 742* Returns: {string[]|null} 743 744Returns an array containing the paths searched during resolution of `request` or 745`null` if the `request` string references a core module, for example `http` or 746`fs`. 747 748## The `module` object 749<!-- YAML 750added: v0.1.16 751--> 752 753<!-- type=var --> 754<!-- name=module --> 755 756* {Object} 757 758In each module, the `module` free variable is a reference to the object 759representing the current module. For convenience, `module.exports` is 760also accessible via the `exports` module-global. `module` is not actually 761a global but rather local to each module. 762 763### `module.children` 764<!-- YAML 765added: v0.1.16 766--> 767 768* {module[]} 769 770The module objects required for the first time by this one. 771 772### `module.exports` 773<!-- YAML 774added: v0.1.16 775--> 776 777* {Object} 778 779The `module.exports` object is created by the `Module` system. Sometimes this is 780not acceptable; many want their module to be an instance of some class. To do 781this, assign the desired export object to `module.exports`. Assigning 782the desired object to `exports` will simply rebind the local `exports` variable, 783which is probably not what is desired. 784 785For example, suppose we were making a module called `a.js`: 786 787```js 788const EventEmitter = require('events'); 789 790module.exports = new EventEmitter(); 791 792// Do some work, and after some time emit 793// the 'ready' event from the module itself. 794setTimeout(() => { 795 module.exports.emit('ready'); 796}, 1000); 797``` 798 799Then in another file we could do: 800 801```js 802const a = require('./a'); 803a.on('ready', () => { 804 console.log('module "a" is ready'); 805}); 806``` 807 808Assignment to `module.exports` must be done immediately. It cannot be 809done in any callbacks. This does not work: 810 811`x.js`: 812 813```js 814setTimeout(() => { 815 module.exports = { a: 'hello' }; 816}, 0); 817``` 818 819`y.js`: 820 821```js 822const x = require('./x'); 823console.log(x.a); 824``` 825 826#### `exports` shortcut 827<!-- YAML 828added: v0.1.16 829--> 830 831The `exports` variable is available within a module's file-level scope, and is 832assigned the value of `module.exports` before the module is evaluated. 833 834It allows a shortcut, so that `module.exports.f = ...` can be written more 835succinctly as `exports.f = ...`. However, be aware that like any variable, if a 836new value is assigned to `exports`, it is no longer bound to `module.exports`: 837 838```js 839module.exports.hello = true; // Exported from require of module 840exports = { hello: false }; // Not exported, only available in the module 841``` 842 843When the `module.exports` property is being completely replaced by a new 844object, it is common to also reassign `exports`: 845 846<!-- eslint-disable func-name-matching --> 847```js 848module.exports = exports = function Constructor() { 849 // ... etc. 850}; 851``` 852 853To illustrate the behavior, imagine this hypothetical implementation of 854`require()`, which is quite similar to what is actually done by `require()`: 855 856```js 857function require(/* ... */) { 858 const module = { exports: {} }; 859 ((module, exports) => { 860 // Module code here. In this example, define a function. 861 function someFunc() {} 862 exports = someFunc; 863 // At this point, exports is no longer a shortcut to module.exports, and 864 // this module will still export an empty default object. 865 module.exports = someFunc; 866 // At this point, the module will now export someFunc, instead of the 867 // default object. 868 })(module, module.exports); 869 return module.exports; 870} 871``` 872 873### `module.filename` 874<!-- YAML 875added: v0.1.16 876--> 877 878* {string} 879 880The fully resolved filename of the module. 881 882### `module.id` 883<!-- YAML 884added: v0.1.16 885--> 886 887* {string} 888 889The identifier for the module. Typically this is the fully resolved 890filename. 891 892### `module.loaded` 893<!-- YAML 894added: v0.1.16 895--> 896 897* {boolean} 898 899Whether or not the module is done loading, or is in the process of 900loading. 901 902### `module.parent` 903<!-- YAML 904added: v0.1.16 905deprecated: 906 - v12.19.0 907 - v14.6.0 908--> 909 910> Stability: 0 - Deprecated: Please use [`require.main`][] and 911> [`module.children`][] instead. 912 913* {module | null | undefined} 914 915The module that first required this one, or `null` if the current module is the 916entry point of the current process, or `undefined` if the module was loaded by 917something that is not a CommonJS module (E.G.: REPL or `import`). 918 919### `module.path` 920<!-- YAML 921added: v11.14.0 922--> 923 924* {string} 925 926The directory name of the module. This is usually the same as the 927[`path.dirname()`][] of the [`module.id`][]. 928 929### `module.paths` 930<!-- YAML 931added: v0.4.0 932--> 933 934* {string[]} 935 936The search paths for the module. 937 938### `module.require(id)` 939<!-- YAML 940added: v0.5.1 941--> 942 943* `id` {string} 944* Returns: {any} exported module content 945 946The `module.require()` method provides a way to load a module as if 947`require()` was called from the original module. 948 949In order to do this, it is necessary to get a reference to the `module` object. 950Since `require()` returns the `module.exports`, and the `module` is typically 951*only* available within a specific module's code, it must be explicitly exported 952in order to be used. 953 954## The `Module` object 955 956This section was moved to 957[Modules: `module` core module](module.html#module_the_module_object). 958 959<!-- Anchors to make sure old links find a target --> 960* <a id="modules_module_builtinmodules" href="module.html#module_module_builtinmodules">`module.builtinModules`</a> 961* <a id="modules_module_createrequire_filename" href="module.html#module_module_createrequire_filename">`module.createRequire(filename)`</a> 962* <a id="modules_module_createrequirefrompath_filename" href="module.html#module_module_createrequirefrompath_filename">`module.createRequireFromPath(filename)`</a> 963* <a id="modules_module_syncbuiltinesmexports" href="module.html#module_module_syncbuiltinesmexports">`module.syncBuiltinESMExports()`</a> 964 965## Source map v3 support 966 967This section was moved to 968[Modules: `module` core module](module.html#module_source_map_v3_support). 969 970<!-- Anchors to make sure old links find a target --> 971* <a id="modules_module_findsourcemap_path_error" href="module.html#module_module_findsourcemap_path_error">`module.findSourceMap(path[, error])`</a> 972* <a id="modules_class_module_sourcemap" href="module.html#module_class_module_sourcemap">Class: `module.SourceMap`</a> 973 * <a id="modules_new_sourcemap_payload" href="module.html#module_new_sourcemap_payload">`new SourceMap(payload)`</a> 974 * <a id="modules_sourcemap_payload" href="module.html#module_sourcemap_payload">`sourceMap.payload`</a> 975 * <a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#module_sourcemap_findentry_linenumber_columnnumber">`sourceMap.findEntry(lineNumber, columnNumber)`</a> 976 977[GLOBAL_FOLDERS]: #modules_loading_from_the_global_folders 978[`Error`]: errors.html#errors_class_error 979[`__dirname`]: #modules_dirname 980[`__filename`]: #modules_filename 981[`module` object]: #modules_the_module_object 982[`module.id`]: #modules_module_id 983[`module.children`]: #modules_module_children 984[`path.dirname()`]: path.html#path_path_dirname_path 985[ECMAScript Modules]: esm.html 986[an error]: errors.html#errors_err_require_esm 987[exports shortcut]: #modules_exports_shortcut 988[module resolution]: #modules_all_together 989[native addons]: addons.html 990[`require.main`]: #modules_require_main 991[`package.json`]: packages.html#packages_node_js_package_json_field_definitions 992[`"main"`]: packages.html#packages_main 993