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