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## 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## 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<pre> 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"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 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"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 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 <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 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</pre> 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<!-- YAML 284changes: 285 - version: v14.18.0 286 pr-url: https://github.com/nodejs/node/pull/37246 287 description: Added `node:` import support to `require(...)`. 288--> 289 290Node.js has several modules compiled into the binary. These modules are 291described in greater detail elsewhere in this documentation. 292 293The core modules are defined within the Node.js source and are located in the 294`lib/` folder. 295 296Core modules are always preferentially loaded if their identifier is 297passed to `require()`. For instance, `require('http')` will always 298return the built in HTTP module, even if there is a file by that name. 299 300Core modules can also be identified using the `node:` prefix, in which case 301it bypasses the `require` cache. For instance, `require('node:http')` will 302always return the built in HTTP module, even if there is `require.cache` entry 303by that name. 304 305## Cycles 306 307<!--type=misc--> 308 309When there are circular `require()` calls, a module might not have finished 310executing when it is returned. 311 312Consider this situation: 313 314`a.js`: 315 316```js 317console.log('a starting'); 318exports.done = false; 319const b = require('./b.js'); 320console.log('in a, b.done = %j', b.done); 321exports.done = true; 322console.log('a done'); 323``` 324 325`b.js`: 326 327```js 328console.log('b starting'); 329exports.done = false; 330const a = require('./a.js'); 331console.log('in b, a.done = %j', a.done); 332exports.done = true; 333console.log('b done'); 334``` 335 336`main.js`: 337 338```js 339console.log('main starting'); 340const a = require('./a.js'); 341const b = require('./b.js'); 342console.log('in main, a.done = %j, b.done = %j', a.done, b.done); 343``` 344 345When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that 346point, `b.js` tries to load `a.js`. In order to prevent an infinite 347loop, an **unfinished copy** of the `a.js` exports object is returned to the 348`b.js` module. `b.js` then finishes loading, and its `exports` object is 349provided to the `a.js` module. 350 351By the time `main.js` has loaded both modules, they're both finished. 352The output of this program would thus be: 353 354```console 355$ node main.js 356main starting 357a starting 358b starting 359in b, a.done = false 360b done 361in a, b.done = true 362a done 363in main, a.done = true, b.done = true 364``` 365 366Careful planning is required to allow cyclic module dependencies to work 367correctly within an application. 368 369## File modules 370 371<!--type=misc--> 372 373If the exact filename is not found, then Node.js will attempt to load the 374required filename with the added extensions: `.js`, `.json`, and finally 375`.node`. 376 377`.js` files are interpreted as JavaScript text files, and `.json` files are 378parsed as JSON text files. `.node` files are interpreted as compiled addon 379modules loaded with `process.dlopen()`. 380 381A required module prefixed with `'/'` is an absolute path to the file. For 382example, `require('/home/marco/foo.js')` will load the file at 383`/home/marco/foo.js`. 384 385A required module prefixed with `'./'` is relative to the file calling 386`require()`. That is, `circle.js` must be in the same directory as `foo.js` for 387`require('./circle')` to find it. 388 389Without a leading `'/'`, `'./'`, or `'../'` to indicate a file, the module must 390either be a core module or is loaded from a `node_modules` folder. 391 392If the given path does not exist, `require()` will throw an [`Error`][] with its 393`code` property set to `'MODULE_NOT_FOUND'`. 394 395## Folders as modules 396 397<!--type=misc--> 398 399It is convenient to organize programs and libraries into self-contained 400directories, and then provide a single entry point to those directories. 401There are three ways in which a folder may be passed to `require()` as 402an argument. 403 404The first is to create a [`package.json`][] file in the root of the folder, 405which specifies a `main` module. An example [`package.json`][] file might 406look like this: 407 408```json 409{ "name" : "some-library", 410 "main" : "./lib/some-library.js" } 411``` 412 413If this was in a folder at `./some-library`, then 414`require('./some-library')` would attempt to load 415`./some-library/lib/some-library.js`. 416 417This is the extent of the awareness of `package.json` files within Node.js. 418 419If there is no [`package.json`][] file present in the directory, or if the 420[`"main"`][] entry is missing or cannot be resolved, then Node.js 421will attempt to load an `index.js` or `index.node` file out of that 422directory. For example, if there was no [`package.json`][] file in the previous 423example, then `require('./some-library')` would attempt to load: 424 425* `./some-library/index.js` 426* `./some-library/index.node` 427 428If these attempts fail, then Node.js will report the entire module as missing 429with the default error: 430 431```console 432Error: Cannot find module 'some-library' 433``` 434 435## Loading from `node_modules` folders 436 437<!--type=misc--> 438 439If the module identifier passed to `require()` is not a 440[core](#modules_core_modules) module, and does not begin with `'/'`, `'../'`, or 441`'./'`, then Node.js starts at the parent directory of the current module, and 442adds `/node_modules`, and attempts to load the module from that location. 443Node.js will not append `node_modules` to a path already ending in 444`node_modules`. 445 446If it is not found there, then it moves to the parent directory, and so 447on, until the root of the file system is reached. 448 449For example, if the file at `'/home/ry/projects/foo.js'` called 450`require('bar.js')`, then Node.js would look in the following locations, in 451this order: 452 453* `/home/ry/projects/node_modules/bar.js` 454* `/home/ry/node_modules/bar.js` 455* `/home/node_modules/bar.js` 456* `/node_modules/bar.js` 457 458This allows programs to localize their dependencies, so that they do not 459clash. 460 461It is possible to require specific files or sub modules distributed with a 462module by including a path suffix after the module name. For instance 463`require('example-module/path/to/file')` would resolve `path/to/file` 464relative to where `example-module` is located. The suffixed path follows the 465same module resolution semantics. 466 467## Loading from the global folders 468 469<!-- type=misc --> 470 471If the `NODE_PATH` environment variable is set to a colon-delimited list 472of absolute paths, then Node.js will search those paths for modules if they 473are not found elsewhere. 474 475On Windows, `NODE_PATH` is delimited by semicolons (`;`) instead of colons. 476 477`NODE_PATH` was originally created to support loading modules from 478varying paths before the current [module resolution][] algorithm was defined. 479 480`NODE_PATH` is still supported, but is less necessary now that the Node.js 481ecosystem has settled on a convention for locating dependent modules. 482Sometimes deployments that rely on `NODE_PATH` show surprising behavior 483when people are unaware that `NODE_PATH` must be set. Sometimes a 484module's dependencies change, causing a different version (or even a 485different module) to be loaded as the `NODE_PATH` is searched. 486 487Additionally, Node.js will search in the following list of GLOBAL_FOLDERS: 488 489* 1: `$HOME/.node_modules` 490* 2: `$HOME/.node_libraries` 491* 3: `$PREFIX/lib/node` 492 493Where `$HOME` is the user's home directory, and `$PREFIX` is the Node.js 494configured `node_prefix`. 495 496These are mostly for historic reasons. 497 498It is strongly encouraged to place dependencies in the local `node_modules` 499folder. These will be loaded faster, and more reliably. 500 501## The module wrapper 502 503<!-- type=misc --> 504 505Before a module's code is executed, Node.js will wrap it with a function 506wrapper that looks like the following: 507 508```js 509(function(exports, require, module, __filename, __dirname) { 510// Module code actually lives in here 511}); 512``` 513 514By doing this, Node.js achieves a few things: 515 516* It keeps top-level variables (defined with `var`, `const` or `let`) scoped to 517 the module rather than the global object. 518* It helps to provide some global-looking variables that are actually specific 519 to the module, such as: 520 * The `module` and `exports` objects that the implementor can use to export 521 values from the module. 522 * The convenience variables `__filename` and `__dirname`, containing the 523 module's absolute filename and directory path. 524 525## The module scope 526 527### `__dirname` 528<!-- YAML 529added: v0.1.27 530--> 531 532<!-- type=var --> 533 534* {string} 535 536The directory name of the current module. This is the same as the 537[`path.dirname()`][] of the [`__filename`][]. 538 539Example: running `node example.js` from `/Users/mjr` 540 541```js 542console.log(__dirname); 543// Prints: /Users/mjr 544console.log(path.dirname(__filename)); 545// Prints: /Users/mjr 546``` 547 548### `__filename` 549<!-- YAML 550added: v0.0.1 551--> 552 553<!-- type=var --> 554 555* {string} 556 557The file name of the current module. This is the current module file's absolute 558path with symlinks resolved. 559 560For a main program this is not necessarily the same as the file name used in the 561command line. 562 563See [`__dirname`][] for the directory name of the current module. 564 565Examples: 566 567Running `node example.js` from `/Users/mjr` 568 569```js 570console.log(__filename); 571// Prints: /Users/mjr/example.js 572console.log(__dirname); 573// Prints: /Users/mjr 574``` 575 576Given two modules: `a` and `b`, where `b` is a dependency of 577`a` and there is a directory structure of: 578 579* `/Users/mjr/app/a.js` 580* `/Users/mjr/app/node_modules/b/b.js` 581 582References to `__filename` within `b.js` will return 583`/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within 584`a.js` will return `/Users/mjr/app/a.js`. 585 586### `exports` 587<!-- YAML 588added: v0.1.12 589--> 590 591<!-- type=var --> 592 593* {Object} 594 595A reference to the `module.exports` that is shorter to type. 596See the section about the [exports shortcut][] for details on when to use 597`exports` and when to use `module.exports`. 598 599### `module` 600<!-- YAML 601added: v0.1.16 602--> 603 604<!-- type=var --> 605 606* {module} 607 608A reference to the current module, see the section about the 609[`module` object][]. In particular, `module.exports` is used for defining what 610a module exports and makes available through `require()`. 611 612### `require(id)` 613<!-- YAML 614added: v0.1.13 615--> 616 617<!-- type=var --> 618 619* `id` {string} module name or path 620* Returns: {any} exported module content 621 622Used to import modules, `JSON`, and local files. Modules can be imported 623from `node_modules`. Local modules and JSON files can be imported using 624a relative path (e.g. `./`, `./foo`, `./bar/baz`, `../foo`) that will be 625resolved against the directory named by [`__dirname`][] (if defined) or 626the current working directory. The relative paths of POSIX style are resolved 627in an OS independent fashion, meaning that the examples above will work on 628Windows in the same way they would on Unix systems. 629 630```js 631// Importing a local module with a path relative to the `__dirname` or current 632// working directory. (On Windows, this would resolve to .\path\myLocalModule.) 633const myLocalModule = require('./path/myLocalModule'); 634 635// Importing a JSON file: 636const jsonData = require('./path/filename.json'); 637 638// Importing a module from node_modules or Node.js built-in module: 639const crypto = require('crypto'); 640``` 641 642#### `require.cache` 643<!-- YAML 644added: v0.3.0 645--> 646 647* {Object} 648 649Modules are cached in this object when they are required. By deleting a key 650value from this object, the next `require` will reload the module. 651This does not apply to [native addons][], for which reloading will result in an 652error. 653 654Adding or replacing entries is also possible. This cache is checked before 655native modules and if a name matching a native module is added to the cache, 656only `node:`-prefixed require calls are going to receive the native module. 657Use with care! 658 659<!-- eslint-disable node-core/no-duplicate-requires --> 660```js 661const assert = require('assert'); 662const realFs = require('fs'); 663 664const fakeFs = {}; 665require.cache.fs = { exports: fakeFs }; 666 667assert.strictEqual(require('fs'), fakeFs); 668assert.strictEqual(require('node:fs'), realFs); 669``` 670 671#### `require.extensions` 672<!-- YAML 673added: v0.3.0 674deprecated: v0.10.6 675--> 676 677> Stability: 0 - Deprecated 678 679* {Object} 680 681Instruct `require` on how to handle certain file extensions. 682 683Process files with the extension `.sjs` as `.js`: 684 685```js 686require.extensions['.sjs'] = require.extensions['.js']; 687``` 688 689**Deprecated.** In the past, this list has been used to load non-JavaScript 690modules into Node.js by compiling them on-demand. However, in practice, there 691are much better ways to do this, such as loading modules via some other Node.js 692program, or compiling them to JavaScript ahead of time. 693 694Avoid using `require.extensions`. Use could cause subtle bugs and resolving the 695extensions gets slower with each registered extension. 696 697#### `require.main` 698<!-- YAML 699added: v0.1.17 700--> 701 702* {module} 703 704The `Module` object representing the entry script loaded when the Node.js 705process launched. 706See ["Accessing the main module"](#modules_accessing_the_main_module). 707 708In `entry.js` script: 709 710```js 711console.log(require.main); 712``` 713 714```bash 715node entry.js 716``` 717 718<!-- eslint-skip --> 719```js 720Module { 721 id: '.', 722 path: '/absolute/path/to', 723 exports: {}, 724 parent: null, 725 filename: '/absolute/path/to/entry.js', 726 loaded: false, 727 children: [], 728 paths: 729 [ '/absolute/path/to/node_modules', 730 '/absolute/path/node_modules', 731 '/absolute/node_modules', 732 '/node_modules' ] } 733``` 734 735#### `require.resolve(request[, options])` 736<!-- YAML 737added: v0.3.0 738changes: 739 - version: v8.9.0 740 pr-url: https://github.com/nodejs/node/pull/16397 741 description: The `paths` option is now supported. 742--> 743 744* `request` {string} The module path to resolve. 745* `options` {Object} 746 * `paths` {string[]} Paths to resolve module location from. If present, these 747 paths are used instead of the default resolution paths, with the exception 748 of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always 749 included. Each of these paths is used as a starting point for 750 the module resolution algorithm, meaning that the `node_modules` hierarchy 751 is checked from this location. 752* Returns: {string} 753 754Use the internal `require()` machinery to look up the location of a module, 755but rather than loading the module, just return the resolved filename. 756 757If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. 758 759##### `require.resolve.paths(request)` 760<!-- YAML 761added: v8.9.0 762--> 763 764* `request` {string} The module path whose lookup paths are being retrieved. 765* Returns: {string[]|null} 766 767Returns an array containing the paths searched during resolution of `request` or 768`null` if the `request` string references a core module, for example `http` or 769`fs`. 770 771## The `module` object 772<!-- YAML 773added: v0.1.16 774--> 775 776<!-- type=var --> 777<!-- name=module --> 778 779* {Object} 780 781In each module, the `module` free variable is a reference to the object 782representing the current module. For convenience, `module.exports` is 783also accessible via the `exports` module-global. `module` is not actually 784a global but rather local to each module. 785 786### `module.children` 787<!-- YAML 788added: v0.1.16 789--> 790 791* {module[]} 792 793The module objects required for the first time by this one. 794 795### `module.exports` 796<!-- YAML 797added: v0.1.16 798--> 799 800* {Object} 801 802The `module.exports` object is created by the `Module` system. Sometimes this is 803not acceptable; many want their module to be an instance of some class. To do 804this, assign the desired export object to `module.exports`. Assigning 805the desired object to `exports` will simply rebind the local `exports` variable, 806which is probably not what is desired. 807 808For example, suppose we were making a module called `a.js`: 809 810```js 811const EventEmitter = require('events'); 812 813module.exports = new EventEmitter(); 814 815// Do some work, and after some time emit 816// the 'ready' event from the module itself. 817setTimeout(() => { 818 module.exports.emit('ready'); 819}, 1000); 820``` 821 822Then in another file we could do: 823 824```js 825const a = require('./a'); 826a.on('ready', () => { 827 console.log('module "a" is ready'); 828}); 829``` 830 831Assignment to `module.exports` must be done immediately. It cannot be 832done in any callbacks. This does not work: 833 834`x.js`: 835 836```js 837setTimeout(() => { 838 module.exports = { a: 'hello' }; 839}, 0); 840``` 841 842`y.js`: 843 844```js 845const x = require('./x'); 846console.log(x.a); 847``` 848 849#### `exports` shortcut 850<!-- YAML 851added: v0.1.16 852--> 853 854The `exports` variable is available within a module's file-level scope, and is 855assigned the value of `module.exports` before the module is evaluated. 856 857It allows a shortcut, so that `module.exports.f = ...` can be written more 858succinctly as `exports.f = ...`. However, be aware that like any variable, if a 859new value is assigned to `exports`, it is no longer bound to `module.exports`: 860 861```js 862module.exports.hello = true; // Exported from require of module 863exports = { hello: false }; // Not exported, only available in the module 864``` 865 866When the `module.exports` property is being completely replaced by a new 867object, it is common to also reassign `exports`: 868 869<!-- eslint-disable func-name-matching --> 870```js 871module.exports = exports = function Constructor() { 872 // ... etc. 873}; 874``` 875 876To illustrate the behavior, imagine this hypothetical implementation of 877`require()`, which is quite similar to what is actually done by `require()`: 878 879```js 880function require(/* ... */) { 881 const module = { exports: {} }; 882 ((module, exports) => { 883 // Module code here. In this example, define a function. 884 function someFunc() {} 885 exports = someFunc; 886 // At this point, exports is no longer a shortcut to module.exports, and 887 // this module will still export an empty default object. 888 module.exports = someFunc; 889 // At this point, the module will now export someFunc, instead of the 890 // default object. 891 })(module, module.exports); 892 return module.exports; 893} 894``` 895 896### `module.filename` 897<!-- YAML 898added: v0.1.16 899--> 900 901* {string} 902 903The fully resolved filename of the module. 904 905### `module.id` 906<!-- YAML 907added: v0.1.16 908--> 909 910* {string} 911 912The identifier for the module. Typically this is the fully resolved 913filename. 914 915### `module.isPreloading` 916<!-- YAML 917added: v14.17.0 918--> 919 920* Type: {boolean} `true` if the module is running during the Node.js preload 921 phase. 922 923### `module.loaded` 924<!-- YAML 925added: v0.1.16 926--> 927 928* {boolean} 929 930Whether or not the module is done loading, or is in the process of 931loading. 932 933### `module.parent` 934<!-- YAML 935added: v0.1.16 936deprecated: 937 - v14.6.0 938 - v12.19.0 939--> 940 941> Stability: 0 - Deprecated: Please use [`require.main`][] and 942> [`module.children`][] instead. 943 944* {module | null | undefined} 945 946The module that first required this one, or `null` if the current module is the 947entry point of the current process, or `undefined` if the module was loaded by 948something that is not a CommonJS module (E.G.: REPL or `import`). 949 950### `module.path` 951<!-- YAML 952added: v11.14.0 953--> 954 955* {string} 956 957The directory name of the module. This is usually the same as the 958[`path.dirname()`][] of the [`module.id`][]. 959 960### `module.paths` 961<!-- YAML 962added: v0.4.0 963--> 964 965* {string[]} 966 967The search paths for the module. 968 969### `module.require(id)` 970<!-- YAML 971added: v0.5.1 972--> 973 974* `id` {string} 975* Returns: {any} exported module content 976 977The `module.require()` method provides a way to load a module as if 978`require()` was called from the original module. 979 980In order to do this, it is necessary to get a reference to the `module` object. 981Since `require()` returns the `module.exports`, and the `module` is typically 982*only* available within a specific module's code, it must be explicitly exported 983in order to be used. 984 985## The `Module` object 986 987This section was moved to 988[Modules: `module` core module](module.md#module_the_module_object). 989 990<!-- Anchors to make sure old links find a target --> 991* <a id="modules_module_builtinmodules" href="module.html#module_module_builtinmodules">`module.builtinModules`</a> 992* <a id="modules_module_createrequire_filename" href="module.html#module_module_createrequire_filename">`module.createRequire(filename)`</a> 993* <a id="modules_module_createrequirefrompath_filename" href="module.html#module_module_createrequirefrompath_filename">`module.createRequireFromPath(filename)`</a> 994* <a id="modules_module_syncbuiltinesmexports" href="module.html#module_module_syncbuiltinesmexports">`module.syncBuiltinESMExports()`</a> 995 996## Source map v3 support 997 998This section was moved to 999[Modules: `module` core module](module.md#module_source_map_v3_support). 1000 1001<!-- Anchors to make sure old links find a target --> 1002* <a id="modules_module_findsourcemap_path_error" href="module.html#module_module_findsourcemap_path">`module.findSourceMap(path)`</a> 1003* <a id="modules_class_module_sourcemap" href="module.html#module_class_module_sourcemap">Class: `module.SourceMap`</a> 1004 * <a id="modules_new_sourcemap_payload" href="module.html#module_new_sourcemap_payload">`new SourceMap(payload)`</a> 1005 * <a id="modules_sourcemap_payload" href="module.html#module_sourcemap_payload">`sourceMap.payload`</a> 1006 * <a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#module_sourcemap_findentry_linenumber_columnnumber">`sourceMap.findEntry(lineNumber, columnNumber)`</a> 1007 1008[ECMAScript Modules]: esm.md 1009[GLOBAL_FOLDERS]: #modules_loading_from_the_global_folders 1010[`"main"`]: packages.md#packages_main 1011[`Error`]: errors.md#errors_class_error 1012[`__dirname`]: #modules_dirname 1013[`__filename`]: #modules_filename 1014[`module.children`]: #modules_module_children 1015[`module.id`]: #modules_module_id 1016[`module` object]: #modules_the_module_object 1017[`package.json`]: packages.md#packages_node_js_package_json_field_definitions 1018[`path.dirname()`]: path.md#path_path_dirname_path 1019[`require.main`]: #modules_require_main 1020[an error]: errors.md#errors_err_require_esm 1021[exports shortcut]: #modules_exports_shortcut 1022[module resolution]: #modules_all_together 1023[native addons]: addons.md 1024