Modules: CommonJS modules#

Stability: 2 - Stable

CommonJS modules are the original way to package JavaScript code for Node.js.Node.js also supports theECMAScript modules standard used by browsersand other JavaScript runtimes.

In Node.js, each file is treated as a separate module. Forexample, consider a file namedfoo.js:

const circle =require('./circle.js');console.log(`The area of a circle of radius 4 is${circle.area(4)}`);

On the first line,foo.js loads the modulecircle.js that is in the samedirectory asfoo.js.

Here are the contents ofcircle.js:

const {PI } =Math;exports.area =(r) =>PI * r **2;exports.circumference =(r) =>2 *PI * r;

The modulecircle.js has exported the functionsarea() andcircumference(). Functions and objects are added to the root of a moduleby specifying additional properties on the specialexports object.

Variables local to the module will be private, because the module is wrappedin a function by Node.js (seemodule wrapper).In this example, the variablePI is private tocircle.js.

Themodule.exports property can be assigned a new value (such as a functionor object).

In the following code,bar.js makes use of thesquare module, which exportsa Square class:

constSquare =require('./square.js');const mySquare =newSquare(2);console.log(`The area of mySquare is${mySquare.area()}`);

Thesquare module is defined insquare.js:

// Assigning to exports will not modify module, must use module.exportsmodule.exports =classSquare {constructor(width) {this.width = width;  }area() {returnthis.width **2;  }};

The CommonJS module system is implemented in themodule core module.

Enabling#

Node.js has two module systems: CommonJS modules andECMAScript modules.

By default, Node.js will treat the following as CommonJS modules:

  • Files with a.cjs extension;

  • Files with a.js extension when the nearest parentpackage.json filecontains a top-level field"type" with a value of"commonjs".

  • Files with a.js extension or without an extension, when the nearest parentpackage.json file doesn't contain a top-level field"type" or there isnopackage.json in any parent folder; unless the file contains syntax thaterrors unless it is evaluated as an ES module. Package authors should includethe"type" field, even in packages where all sources are CommonJS. Beingexplicit about thetype of the package will make things easier for buildtools and loaders to determine how the files in the package should beinterpreted.

  • Files with an extension that is not.mjs,.cjs,.json,.node, or.js(when the nearest parentpackage.json file contains a top-level field"type" with a value of"module", those files will be recognized asCommonJS modules only if they are being included viarequire(), not whenused as the command-line entry point of the program).

SeeDetermining module system for more details.

Callingrequire() always use the CommonJS module loader. Callingimport()always use the ECMAScript module loader.

Accessing the main module#

When a file is run directly from Node.js,require.main is set to itsmodule. That means that it is possible to determine whether a file has beenrun directly by testingrequire.main === module.

For a filefoo.js, this will betrue if run vianode foo.js, butfalse if run byrequire('./foo').

When the entry point is not a CommonJS module,require.main isundefined,and the main module is out of reach.

Package manager tips#

The semantics of the Node.jsrequire() function were designed to be generalenough to support reasonable directory structures. Package manager programssuch asdpkg,rpm, andnpm will hopefully find it possible to buildnative packages from Node.js modules without modification.

In the following, we give a suggested directory structure that could work:

Let's say that we wanted to have the folder at/usr/lib/node/<some-package>/<some-version> hold the contents of aspecific version of a package.

Packages can depend on one another. In order to install packagefoo, itmay be necessary to install a specific version of packagebar. Thebarpackage may itself have dependencies, and in some cases, these may even collideor form cyclic dependencies.

Because Node.js looks up therealpath of any modules it loads (that is, itresolves symlinks) and thenlooks for their dependencies innode_modules folders,this situation can be resolved with the following architecture:

  • /usr/lib/node/foo/1.2.3/: Contents of thefoo package, version 1.2.3.
  • /usr/lib/node/bar/4.3.2/: Contents of thebar package thatfoo dependson.
  • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to/usr/lib/node/bar/4.3.2/.
  • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages thatbar depends on.

Thus, even if a cycle is encountered, or if there are dependencyconflicts, every module will be able to get a version of its dependencythat it can use.

When the code in thefoo package doesrequire('bar'), it will get theversion that is symlinked into/usr/lib/node/foo/1.2.3/node_modules/bar.Then, when the code in thebar package callsrequire('quux'), it'll getthe version that is symlinked into/usr/lib/node/bar/4.3.2/node_modules/quux.

Furthermore, to make the module lookup process even more optimal, ratherthan putting packages directly in/usr/lib/node, we could put them in/usr/lib/node_modules/<name>/<version>. Then Node.js will not botherlooking for missing dependencies in/usr/node_modules or/node_modules.

In order to make modules available to the Node.js REPL, it might be useful toalso add the/usr/lib/node_modules folder to the$NODE_PATH environmentvariable. Since the module lookups usingnode_modules folders are allrelative, and based on the real path of the files making the calls torequire(), the packages themselves can be anywhere.

Loading ECMAScript modules usingrequire()#

History
VersionChanges
v23.0.0, v22.12.0

Support'module.exports' interop export inrequire(esm).

v23.5.0, v22.13.0, v20.19.0

This feature no longer emits an experimental warning by default, though the warning can still be emitted by --trace-require-module.

v23.0.0, v22.12.0, v20.19.0

This feature is no longer behind the--experimental-require-module CLI flag.

v22.0.0, v20.17.0

Added in: v22.0.0, v20.17.0

Stability: 1.2 - Release candidate

The.mjs extension is reserved forECMAScript Modules.SeeDetermining module system section for more inforegarding which files are parsed as ECMAScript modules.

require() only supports loading ECMAScript modules that meet the following requirements:

  • The module is fully synchronous (contains no top-levelawait); and
  • One of these conditions are met:
    1. The file has a.mjs extension.
    2. The file has a.js extension, and the closestpackage.json contains"type": "module"
    3. The file has a.js extension, the closestpackage.json does not contain"type": "commonjs", and the module contains ES module syntax.

If the ES Module being loaded meets the requirements,require() can load it andreturn themodule namespace object. In this case it is similar to dynamicimport() but is run synchronously and returns the name space objectdirectly.

With the following ES Modules:

// distance.mjsexportfunctiondistance(a, b) {returnMath.sqrt((b.x - a.x) **2 + (b.y - a.y) **2); }
// point.mjsexportdefaultclassPoint {constructor(x, y) {this.x = x;this.y = y; }}

A CommonJS module can load them withrequire():

const distance =require('./distance.mjs');console.log(distance);// [Module: null prototype] {//   distance: [Function: distance]// }const point =require('./point.mjs');console.log(point);// [Module: null prototype] {//   default: [class Point],//   __esModule: true,// }

For interoperability with existing tools that convert ES Modules into CommonJS,which could then load real ES Modules throughrequire(), the returned namespacewould contain a__esModule: true property if it has adefault export so thatconsuming code generated by tools can recognize the default exports in realES Modules. If the namespace already defines__esModule, this would not be added.This property is experimental and can change in the future. It should only be usedby tools converting ES modules into CommonJS modules, following existing ecosystemconventions. Code authored directly in CommonJS should avoid depending on it.

When an ES Module contains both named exports and a default export, the result returned byrequire()is themodule namespace object, which places the default export in the.default property, similar tothe results returned byimport().To customize what should be returned byrequire(esm) directly, the ES Module can export thedesired value using the string name"module.exports".

// point.mjsexportdefaultclassPoint {constructor(x, y) {this.x = x;this.y = y; }}// `distance` is lost to CommonJS consumers of this module, unless it's// added to `Point` as a static property.exportfunctiondistance(a, b) {returnMath.sqrt((b.x - a.x) **2 + (b.y - a.y) **2); }export {Pointas'module.exports' }
constPoint =require('./point.mjs');console.log(Point);// [class Point]// Named exports are lost when 'module.exports' is usedconst { distance } =require('./point.mjs');console.log(distance);// undefined

Notice in the example above, when themodule.exports export name is used, named exportswill be lost to CommonJS consumers. To allow CommonJS consumers to continue accessingnamed exports, the module can make sure that the default export is an object with thenamed exports attached to it as properties. For example with the example above,distance can be attached to the default export, thePoint class, as a static method.

exportfunctiondistance(a, b) {returnMath.sqrt((b.x - a.x) **2 + (b.y - a.y) **2); }exportdefaultclassPoint {constructor(x, y) {this.x = x;this.y = y; }static distance = distance;}export {Pointas'module.exports' }
constPoint =require('./point.mjs');console.log(Point);// [class Point]const { distance } =require('./point.mjs');console.log(distance);// [Function: distance]

If the module beingrequire()'d contains top-levelawait, or the modulegraph itimports contains top-levelawait,ERR_REQUIRE_ASYNC_MODULE will be thrown. In this case, users shouldload the asynchronous module usingimport().

If--experimental-print-required-tla is enabled, instead of throwingERR_REQUIRE_ASYNC_MODULE before evaluation, Node.js will evaluate themodule, try to locate the top-level awaits, and print their location tohelp users fix them.

Support for loading ES modules usingrequire() is currentlyexperimental and can be disabled using--no-experimental-require-module.To print where this feature is used, use--trace-require-module.

This feature can be detected by checking ifprocess.features.require_module istrue.

All together#

To get the exact filename that will be loaded whenrequire() is called, usetherequire.resolve() function.

Putting together all of the above, here is the high-level algorithmin pseudocode of whatrequire() does:

require(X) from module at path Y1. If X is a core module,   a. return the core module   b. STOP2. If X begins with '/'   a. set Y to the file system root3. If X is equal to '.', or X begins with './', '/' or '../'   a. LOAD_AS_FILE(Y + X)   b. LOAD_AS_DIRECTORY(Y + X)   c. THROW "not found"4. If X begins with '#'   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))5. LOAD_PACKAGE_SELF(X, dirname(Y))6. LOAD_NODE_MODULES(X, dirname(Y))7. THROW "not found"MAYBE_DETECT_AND_LOAD(X)1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.2. Else, if the source code of X can be parsed as ECMAScript module using  <a href="esm.md#resolver-algorithm-specification">DETECT_MODULE_SYNTAX defined in  the ESM resolver</a>,  a. Load X as an ECMAScript module. STOP.3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP.LOAD_AS_FILE(X)1. If X is a file, load X as its file extension format. STOP2. If X.js is a file,    a. Find the closest package scope SCOPE to X.    b. If no scope was found      1. MAYBE_DETECT_AND_LOAD(X.js)    c. If the SCOPE/package.json contains "type" field,      1. If the "type" field is "module", load X.js as an ECMAScript module. STOP.      2. If the "type" field is "commonjs", load X.js as a CommonJS module. STOP.    d. MAYBE_DETECT_AND_LOAD(X.js)3. If X.json is a file, load X.json to a JavaScript Object. STOP4. If X.node is a file, load X.node as binary addon. STOPLOAD_INDEX(X)1. If X/index.js is a file    a. Find the closest package scope SCOPE to X.    b. If no scope was found, load X/index.js as a CommonJS module. STOP.    c. If the SCOPE/package.json contains "type" field,      1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP.      2. Else, load X/index.js as a CommonJS module. STOP.2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP3. If X/index.node is a file, load X/index.node as binary addon. STOPLOAD_AS_DIRECTORY(X)1. If X/package.json is a file,   a. Parse X/package.json, and look for "main" field.   b. If "main" is a falsy value, GOTO 2.   c. let M = X + (json main field)   d. LOAD_AS_FILE(M)   e. LOAD_INDEX(M)   f. LOAD_INDEX(X) DEPRECATED   g. THROW "not found"2. LOAD_INDEX(X)LOAD_NODE_MODULES(X, START)1. let DIRS = NODE_MODULES_PATHS(START)2. for each DIR in DIRS:   a. LOAD_PACKAGE_EXPORTS(X, DIR)   b. LOAD_AS_FILE(DIR/X)   c. LOAD_AS_DIRECTORY(DIR/X)NODE_MODULES_PATHS(START)1. let PARTS = path split(START)2. let I = count of PARTS - 13. let DIRS = []4. while I >= 0,   a. if PARTS[I] = "node_modules", GOTO d.   b. DIR = path join(PARTS[0 .. I] + "node_modules")   c. DIRS = DIR + DIRS   d. let I = I - 15. return DIRS + GLOBAL_FOLDERSLOAD_PACKAGE_IMPORTS(X, DIR)1. Find the closest package scope SCOPE to DIR.2. If no scope was found, return.3. If the SCOPE/package.json "imports" is null or undefined, return.4. If `--experimental-require-module` is enabled  a. let CONDITIONS = ["node", "require", "module-sync"]  b. Else, let CONDITIONS = ["node", "require"]5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),  CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.6. RESOLVE_ESM_MATCH(MATCH).LOAD_PACKAGE_EXPORTS(X, DIR)1. Try to interpret X as a combination of NAME and SUBPATH where the name   may have a @scope/ prefix and the subpath begins with a slash (`/`).2. If X does not match this pattern or DIR/NAME/package.json is not a file,   return.3. Parse DIR/NAME/package.json, and look for "exports" field.4. If "exports" is null or undefined, return.5. If `--experimental-require-module` is enabled  a. let CONDITIONS = ["node", "require", "module-sync"]  b. Else, let CONDITIONS = ["node", "require"]6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,   `package.json` "exports", CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.7. RESOLVE_ESM_MATCH(MATCH)LOAD_PACKAGE_SELF(X, DIR)1. Find the closest package scope SCOPE to DIR.2. If no scope was found, return.3. If the SCOPE/package.json "exports" is null or undefined, return.4. If the SCOPE/package.json "name" is not the first segment of X, return.5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),   "." + X.slice("name".length), `package.json` "exports", ["node", "require"])   <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.6. RESOLVE_ESM_MATCH(MATCH)RESOLVE_ESM_MATCH(MATCH)1. let RESOLVED_PATH = fileURLToPath(MATCH)2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension   format. STOP3. THROW "not found"

Caching#

Modules are cached after the first time they are loaded. This means (among otherthings) that every call torequire('foo') will get exactly the same objectreturned, if it would resolve to the same file.

Providedrequire.cache is not modified, multiple calls torequire('foo')will not cause the module code to be executed multiple times. This is animportant feature. With it, "partially done" objects can be returned, thusallowing transitive dependencies to be loaded even when they would cause cycles.

To have a module execute code multiple times, export a function, and call thatfunction.

Module caching caveats#

Modules are cached based on their resolved filename. Since modules may resolveto a different filename based on the location of the calling module (loadingfromnode_modules folders), it is not aguarantee thatrequire('foo') willalways return the exact same object, if it would resolve to different files.

Additionally, on case-insensitive file systems or operating systems, differentresolved filenames can point to the same file, but the cache will still treatthem as different modules and will reload the file multiple times. For example,require('./foo') andrequire('./FOO') return two different objects,irrespective of whether or not./foo and./FOO are the same file.

Built-in modules#

History
VersionChanges
v16.0.0, v14.18.0

Addednode: import support torequire(...).

Node.js has several modules compiled into the binary. These modules aredescribed in greater detail elsewhere in this documentation.

The built-in modules are defined within the Node.js source and are located in thelib/ folder.

Built-in modules can be identified using thenode: prefix, in which caseit bypasses therequire cache. For instance,require('node:http') willalways return the built in HTTP module, even if there isrequire.cache entryby that name.

Some built-in modules are always preferentially loaded if their identifier ispassed torequire(). For instance,require('http') will alwaysreturn the built-in HTTP module, even if there is a file by that name.

The list of all the built-in modules can be retrieved frommodule.builtinModules.The modules being all listed without thenode: prefix, except those that mandate suchprefix (as explained in the next section).

Built-in modules with mandatorynode: prefix#

When being loaded byrequire(), some built-in modules must be requested with thenode: prefix. This requirement exists to prevent newly introduced built-inmodules from having a conflict with user land packages that already havetaken the name. Currently the built-in modules that requires thenode: prefix are:

The list of these modules is exposed inmodule.builtinModules, including the prefix.

Cycles#

When there are circularrequire() calls, a module might not have finishedexecuting when it is returned.

Consider this situation:

a.js:

console.log('a starting');exports.done =false;const b =require('./b.js');console.log('in a, b.done = %j', b.done);exports.done =true;console.log('a done');

b.js:

console.log('b starting');exports.done =false;const a =require('./a.js');console.log('in b, a.done = %j', a.done);exports.done =true;console.log('b done');

main.js:

console.log('main starting');const a =require('./a.js');const b =require('./b.js');console.log('in main, a.done = %j, b.done = %j', a.done, b.done);

Whenmain.js loadsa.js, thena.js in turn loadsb.js. At thatpoint,b.js tries to loada.js. In order to prevent an infiniteloop, anunfinished copy of thea.js exports object is returned to theb.js module.b.js then finishes loading, and itsexports object isprovided to thea.js module.

By the timemain.js has loaded both modules, they're both finished.The output of this program would thus be:

$node main.jsmain startinga startingb startingin b, a.done = falseb donein a, b.done = truea donein main, a.done = true, b.done = true

Careful planning is required to allow cyclic module dependencies to workcorrectly within an application.

File modules#

If the exact filename is not found, then Node.js will attempt to load therequired filename with the added extensions:.js,.json, and finally.node. When loading a file that has a different extension (e.g..cjs), itsfull name must be passed torequire(), including its file extension (e.g.require('./file.cjs')).

.json files are parsed as JSON text files,.node files are interpreted ascompiled addon modules loaded withprocess.dlopen(). Files using any otherextension (or no extension at all) are parsed as JavaScript text files. Refer totheDetermining module system section to understand what parse goal will beused.

A required module prefixed with'/' is an absolute path to the file. Forexample,require('/home/marco/foo.js') will load the file at/home/marco/foo.js.

A required module prefixed with'./' is relative to the file callingrequire(). That is,circle.js must be in the same directory asfoo.js forrequire('./circle') to find it.

Without a leading'/','./', or'../' to indicate a file, the module musteither be a core module or is loaded from anode_modules folder.

If the given path does not exist,require() will throw aMODULE_NOT_FOUND error.

Folders as modules#

Stability: 3 - Legacy: Usesubpath exports orsubpath imports instead.

There are three ways in which a folder may be passed torequire() asan argument.

The first is to create apackage.json file in the root of the folder,which specifies amain module. An examplepackage.json file mightlook like this:

{"name":"some-library","main":"./lib/some-library.js"}

If this was in a folder at./some-library, thenrequire('./some-library') would attempt to load./some-library/lib/some-library.js.

If there is nopackage.json file present in the directory, or if the"main" entry is missing or cannot be resolved, then Node.jswill attempt to load anindex.js orindex.node file out of thatdirectory. For example, if there was nopackage.json file in the previousexample, thenrequire('./some-library') would attempt to load:

  • ./some-library/index.js
  • ./some-library/index.node

If these attempts fail, then Node.js will report the entire module as missingwith the default error:

Error: Cannot find module 'some-library'

In all three above cases, animport('./some-library') call would result in aERR_UNSUPPORTED_DIR_IMPORT error. Using packagesubpath exports orsubpath imports can provide the same containment organization benefits asfolders as modules, and work for bothrequire andimport.

Loading fromnode_modules folders#

If the module identifier passed torequire() is not abuilt-in module, and does not begin with'/','../', or'./', then Node.js starts at the directory of the current module, andadds/node_modules, and attempts to load the module from that location.Node.js will not appendnode_modules to a path already ending innode_modules.

If it is not found there, then it moves to the parent directory, and soon, until the root of the file system is reached.

For example, if the file at'/home/ry/projects/foo.js' calledrequire('bar.js'), then Node.js would look in the following locations, inthis order:

  • /home/ry/projects/node_modules/bar.js
  • /home/ry/node_modules/bar.js
  • /home/node_modules/bar.js
  • /node_modules/bar.js

This allows programs to localize their dependencies, so that they do notclash.

It is possible to require specific files or sub modules distributed with amodule by including a path suffix after the module name. For instancerequire('example-module/path/to/file') would resolvepath/to/filerelative to whereexample-module is located. The suffixed path follows thesame module resolution semantics.

Loading from the global folders#

If theNODE_PATH environment variable is set to a colon-delimited listof absolute paths, then Node.js will search those paths for modules if theyare not found elsewhere.

On Windows,NODE_PATH is delimited by semicolons (;) instead of colons.

NODE_PATH was originally created to support loading modules fromvarying paths before the currentmodule resolution algorithm was defined.

NODE_PATH is still supported, but is less necessary now that the Node.jsecosystem has settled on a convention for locating dependent modules.Sometimes deployments that rely onNODE_PATH show surprising behaviorwhen people are unaware thatNODE_PATH must be set. Sometimes amodule's dependencies change, causing a different version (or even adifferent module) to be loaded as theNODE_PATH is searched.

Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

  • 1:$HOME/.node_modules
  • 2:$HOME/.node_libraries
  • 3:$PREFIX/lib/node

Where$HOME is the user's home directory, and$PREFIX is the Node.jsconfigurednode_prefix.

These are mostly for historic reasons.

It is strongly encouraged to place dependencies in the localnode_modulesfolder. These will be loaded faster, and more reliably.

The module wrapper#

Before a module's code is executed, Node.js will wrap it with a functionwrapper that looks like the following:

(function(exports,require,module, __filename, __dirname) {// Module code actually lives in here});

By doing this, Node.js achieves a few things:

  • It keeps top-level variables (defined withvar,const, orlet) scoped tothe module rather than the global object.
  • It helps to provide some global-looking variables that are actually specificto the module, such as:
    • Themodule andexports objects that the implementor can use to exportvalues from the module.
    • The convenience variables__filename and__dirname, containing themodule's absolute filename and directory path.

The module scope#

__dirname#

Added in: v0.1.27

The directory name of the current module. This is the same as thepath.dirname() of the__filename.

Example: runningnode example.js from/Users/mjr

console.log(__dirname);// Prints: /Users/mjrconsole.log(path.dirname(__filename));// Prints: /Users/mjr

__filename#

Added in: v0.0.1

The file name of the current module. This is the current module file's absolutepath with symlinks resolved.

For a main program this is not necessarily the same as the file name used in thecommand line.

See__dirname for the directory name of the current module.

Examples:

Runningnode example.js from/Users/mjr

console.log(__filename);// Prints: /Users/mjr/example.jsconsole.log(__dirname);// Prints: /Users/mjr

Given two modules:a andb, whereb is a dependency ofa and there is a directory structure of:

  • /Users/mjr/app/a.js
  • /Users/mjr/app/node_modules/b/b.js

References to__filename withinb.js will return/Users/mjr/app/node_modules/b/b.js while references to__filename withina.js will return/Users/mjr/app/a.js.

exports#

Added in: v0.1.12

A reference to themodule.exports that is shorter to type.See the section about theexports shortcut for details on when to useexports and when to usemodule.exports.

module#

Added in: v0.1.16

A reference to the current module, see the section about themodule object. In particular,module.exports is used for defining whata module exports and makes available throughrequire().

require(id)#

Added in: v0.1.13
  • id<string> module name or path
  • Returns:<any> exported module content

Used to import modules,JSON, and local files. Modules can be importedfromnode_modules. Local modules and JSON files can be imported usinga relative path (e.g../,./foo,./bar/baz,../foo) that will beresolved against the directory named by__dirname (if defined) orthe current working directory. The relative paths of POSIX style are resolvedin an OS independent fashion, meaning that the examples above will work onWindows in the same way they would on Unix systems.

// Importing a local module with a path relative to the `__dirname` or current// working directory. (On Windows, this would resolve to .\path\myLocalModule.)const myLocalModule =require('./path/myLocalModule');// Importing a JSON file:const jsonData =require('./path/filename.json');// Importing a module from node_modules or Node.js built-in module:const crypto =require('node:crypto');
require.cache#
Added in: v0.3.0

Modules are cached in this object when they are required. By deleting a keyvalue from this object, the nextrequire will reload the module.This does not apply tonative addons, for which reloading will result in anerror.

Adding or replacing entries is also possible. This cache is checked beforebuilt-in modules and if a name matching a built-in module is added to the cache,onlynode:-prefixed require calls are going to receive the built-in module.Use with care!

const assert =require('node:assert');const realFs =require('node:fs');const fakeFs = {};require.cache.fs = {exports: fakeFs };assert.strictEqual(require('fs'), fakeFs);assert.strictEqual(require('node:fs'), realFs);
require.extensions#
Added in: v0.3.0Deprecated since: v0.10.6

Stability: 0 - Deprecated

Instructrequire on how to handle certain file extensions.

Process files with the extension.sjs as.js:

require.extensions['.sjs'] =require.extensions['.js'];

Deprecated. In the past, this list has been used to load non-JavaScriptmodules into Node.js by compiling them on-demand. However, in practice, thereare much better ways to do this, such as loading modules via some other Node.jsprogram, or compiling them to JavaScript ahead of time.

Avoid usingrequire.extensions. Use could cause subtle bugs and resolving theextensions gets slower with each registered extension.

require.main#
Added in: v0.1.17

TheModule object representing the entry script loaded when the Node.jsprocess launched, orundefined if the entry point of the program is not aCommonJS module.See"Accessing the main module".

Inentry.js script:

console.log(require.main);
node entry.js
Module {id:'.',path:'/absolute/path/to',exports: {},filename:'/absolute/path/to/entry.js',loaded:false,children: [],paths:   ['/absolute/path/to/node_modules','/absolute/path/node_modules','/absolute/node_modules','/node_modules' ] }
require.resolve(request[, options])#
History
VersionChanges
v8.9.0

Thepaths option is now supported.

v0.3.0

Added in: v0.3.0

  • request<string> The module path to resolve.
  • options<Object>
    • paths<string[]> Paths to resolve module location from. If present, thesepaths are used instead of the default resolution paths, with the exceptionofGLOBAL_FOLDERS like$HOME/.node_modules, which arealways included. Each of these paths is used as a starting point forthe module resolution algorithm, meaning that thenode_modules hierarchyis checked from this location.
  • Returns:<string>

Use the internalrequire() machinery to look up the location of a module,but rather than loading the module, just return the resolved filename.

If the module can not be found, aMODULE_NOT_FOUND error is thrown.

require.resolve.paths(request)#
Added in: v8.9.0

Returns an array containing the paths searched during resolution ofrequest ornull if therequest string references a core module, for examplehttp orfs.

Themodule object#

Added in: v0.1.16

In each module, themodule free variable is a reference to the objectrepresenting the current module. For convenience,module.exports isalso accessible via theexports module-global.module is not actuallya global but rather local to each module.

module.children#

Added in: v0.1.16

The module objects required for the first time by this one.

module.exports#

Added in: v0.1.16

Themodule.exports object is created by theModule system. Sometimes this isnot acceptable; many want their module to be an instance of some class. To dothis, assign the desired export object tomodule.exports. Assigningthe desired object toexports will simply rebind the localexports variable,which is probably not what is desired.

For example, suppose we were making a module calleda.js:

constEventEmitter =require('node:events');module.exports =newEventEmitter();// Do some work, and after some time emit// the 'ready' event from the module itself.setTimeout(() => {module.exports.emit('ready');},1000);

Then in another file we could do:

const a =require('./a');a.on('ready',() => {console.log('module "a" is ready');});

Assignment tomodule.exports must be done immediately. It cannot bedone in any callbacks. This does not work:

x.js:

setTimeout(() => {module.exports = {a:'hello' };},0);

y.js:

const x =require('./x');console.log(x.a);
exports shortcut#
Added in: v0.1.16

Theexports variable is available within a module's file-level scope, and isassigned the value ofmodule.exports before the module is evaluated.

It allows a shortcut, so thatmodule.exports.f = ... can be written moresuccinctly asexports.f = .... However, be aware that like any variable, if anew value is assigned toexports, it is no longer bound tomodule.exports:

module.exports.hello =true;// Exported from require of moduleexports = {hello:false };// Not exported, only available in the module

When themodule.exports property is being completely replaced by a newobject, it is common to also reassignexports:

module.exports =exports =functionConstructor() {// ... etc.};

To illustrate the behavior, imagine this hypothetical implementation ofrequire(), which is quite similar to what is actually done byrequire():

functionrequire(/* ... */) {constmodule = {exports: {} };  ((module,exports) => {// Module code here. In this example, define a function.functionsomeFunc() {}exports = someFunc;// At this point, exports is no longer a shortcut to module.exports, and// this module will still export an empty default object.module.exports = someFunc;// At this point, the module will now export someFunc, instead of the// default object.  })(module,module.exports);returnmodule.exports;}

module.filename#

Added in: v0.1.16

The fully resolved filename of the module.

module.id#

Added in: v0.1.16

The identifier for the module. Typically this is the fully resolvedfilename.

module.isPreloading#

Added in: v15.4.0, v14.17.0
  • Type:<boolean>true if the module is running during the Node.js preloadphase.

module.loaded#

Added in: v0.1.16

Whether or not the module is done loading, or is in the process ofloading.

module.parent#

Added in: v0.1.16Deprecated since: v14.6.0, v12.19.0

Stability: 0 - Deprecated: Please userequire.main andmodule.children instead.

The module that first required this one, ornull if the current module is theentry point of the current process, orundefined if the module was loaded bysomething that is not a CommonJS module (E.G.: REPL orimport).

module.path#

Added in: v11.14.0

The directory name of the module. This is usually the same as thepath.dirname() of themodule.id.

module.paths#

Added in: v0.4.0

The search paths for the module.

module.require(id)#

Added in: v0.5.1

Themodule.require() method provides a way to load a module as ifrequire() was called from the original module.

In order to do this, it is necessary to get a reference to themodule object.Sincerequire() returns themodule.exports, and themodule is typicallyonly available within a specific module's code, it must be explicitly exportedin order to be used.

TheModule object#

This section was moved toModules:module core module.

Source map v3 support#

This section was moved toModules:module core module.