{ "type": "module", "source": "doc/api/modules.md", "modules": [ { "textRaw": "Modules", "name": "module", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

In the Node.js module system, each file is treated as a separate module. For\nexample, consider a file named foo.js:

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

On the first line, foo.js loads the module circle.js that is in the same\ndirectory as foo.js.

\n

Here are the contents of circle.js:

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

The module circle.js has exported the functions area() and\ncircumference(). Functions and objects are added to the root of a module\nby specifying additional properties on the special exports object.

\n

Variables local to the module will be private, because the module is wrapped\nin a function by Node.js (see module wrapper).\nIn this example, the variable PI is private to circle.js.

\n

The module.exports property can be assigned a new value (such as a function\nor object).

\n

Below, bar.js makes use of the square module, which exports a Square class:

\n
const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n
\n

The square module is defined in square.js:

\n
// Assigning to exports will not modify module, must use module.exports\nmodule.exports = class Square {\n  constructor(width) {\n    this.width = width;\n  }\n\n  area() {\n    return this.width ** 2;\n  }\n};\n
\n

The module system is implemented in the require('module') module.

", "miscs": [ { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

When a file is run directly from Node.js, require.main is set to its\nmodule. That means that it is possible to determine whether a file has been\nrun directly by testing require.main === module.

\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.

" }, { "textRaw": "Addenda: Package manager tips", "name": "Addenda: Package manager tips", "type": "misc", "desc": "

The semantics of the Node.js require() function were designed to be general\nenough to support reasonable directory structures. Package manager programs\nsuch as dpkg, rpm, and npm will hopefully find it possible to build\nnative packages from Node.js modules without modification.

\n

Below we give a suggested directory structure that could work:

\n

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

\n

Packages can depend on one another. In order to install package foo, it\nmay be necessary to install a specific version of package bar. The bar\npackage may itself have dependencies, and in some cases, these may even collide\nor form cyclic dependencies.

\n

Since Node.js looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the node_modules\nfolders as described here, this\nsituation is very simple to resolve with the following architecture:

\n\n

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

\n

When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.

\n

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

\n

In order to make modules available to the Node.js REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.

" }, { "textRaw": "All together...", "name": "All together...", "type": "misc", "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require() does:

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with '/'\n   a. set Y to be the filesystem root\n3. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n   c. THROW \"not found\"\n4. If X begins with '#'\n   a. LOAD_INTERAL_IMPORT(X, Y)\n4. LOAD_SELF_REFERENCE(X, Y)\n5. LOAD_NODE_MODULES(X, dirname(Y))\n6. THROW \"not found\"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as its file extension format. STOP\n2. If X.js is a file, load X.js as JavaScript text. STOP\n3. If X.json is a file, parse X.json to a JavaScript Object. STOP\n4. If X.node is a file, load X.node as binary addon. STOP\n\nLOAD_INDEX(X)\n1. If X/index.js is a file, load X/index.js as JavaScript text. STOP\n2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n3. If X/index.node is a file, load X/index.node as binary addon. STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for \"main\" field.\n   b. If \"main\" is a falsy value, GOTO 2.\n   c. let M = X + (json main field)\n   d. LOAD_AS_FILE(M)\n   e. LOAD_INDEX(M)\n   f. LOAD_INDEX(X) DEPRECATED\n   g. THROW \"not found\"\n2. LOAD_INDEX(X)\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS = NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_PACKAGE_EXPORTS(DIR, X)\n   b. LOAD_AS_FILE(DIR/X)\n   c. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = [GLOBAL_FOLDERS]\n4. while I >= 0,\n   a. if PARTS[I] = \"node_modules\" CONTINUE\n   b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n   c. DIRS = DIRS + DIR\n   d. let I = I - 1\n5. return DIRS\n\nLOAD_SELF_REFERENCE(X, START)\n1. Find the closest package scope to START.\n2. If no scope was found, return.\n3. If the `package.json` has no \"exports\", return.\n4. If the name in `package.json` is a prefix of X, then\n   a. Load the remainder of X relative to this package as if it was\n      loaded via `LOAD_NODE_MODULES` with a name in `package.json`.\n\nLOAD_PACKAGE_EXPORTS(DIR, X)\n1. Try to interpret X as a combination of name and subpath where the name\n   may have a @scope/ prefix and the subpath begins with a slash (`/`).\n2. If X does not match this pattern or DIR/name/package.json is not a file,\n   return.\n3. Parse DIR/name/package.json, and look for \"exports\" field.\n4. If \"exports\" is null or undefined, return.\n5. If \"exports\" is an object with some keys starting with \".\" and some keys\n  not starting with \".\", throw \"invalid config\".\n6. If \"exports\" is a string, or object with no keys starting with \".\", treat\n  it as having that value as its \".\" object property.\n7. If subpath is \".\" and \"exports\" does not have a \".\" entry, return.\n8. Find the longest key in \"exports\" that the subpath starts with.\n9. If no such key can be found, throw \"not found\".\n10. let RESOLVED =\n    fileURLToPath(PACKAGE_EXPORTS_TARGET_RESOLVE(pathToFileURL(DIR/name),\n    exports[key], subpath.slice(key.length), [\"node\", \"require\"])), as defined\n    in the ESM resolver.\n11. If key ends with \"/\":\n    a. LOAD_AS_FILE(RESOLVED)\n    b. LOAD_AS_DIRECTORY(RESOLVED)\n12. Otherwise\n   a. If RESOLVED is a file, load it as its file extension format. STOP\n13. Throw \"not found\"\n\nLOAD_INTERNAL_IMPORT(X, START)\n1. Find the closest package scope to START.\n2. If no scope was found or the `package.json` has no \"imports\", return.\n3. let RESOLVED =\n  fileURLToPath(PACKAGE_INTERNAL_RESOLVE(X, pathToFileURL(START)), as defined\n  in the ESM resolver.\n4. If RESOLVED is not a valid file, throw \"not found\"\n5. Load RESOLVED as its file extension format. STOP\n
" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

Modules are cached after the first time they are loaded. This means (among other\nthings) that every call to require('foo') will get exactly the same object\nreturned, if it would resolve to the same file.

\n

Provided require.cache is not modified, multiple calls to require('foo')\nwill not cause the module code to be executed multiple times. This is an\nimportant feature. With it, \"partially done\" objects can be returned, thus\nallowing transitive dependencies to be loaded even when they would cause cycles.

\n

To have a module execute code multiple times, export a function, and call that\nfunction.

", "miscs": [ { "textRaw": "Module caching caveats", "name": "Module caching caveats", "type": "misc", "desc": "

Modules are cached based on their resolved filename. Since modules may resolve\nto a different filename based on the location of the calling module (loading\nfrom node_modules folders), it is not a guarantee that require('foo') will\nalways return the exact same object, if it would resolve to different files.

\n

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

" } ] }, { "textRaw": "Core modules", "name": "Core modules", "type": "misc", "desc": "

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

\n

The core modules are defined within the Node.js source and are located in the\nlib/ folder.

\n

Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.

" }, { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

When there are circular require() calls, a module might not have finished\nexecuting when it is returned.

\n

Consider this situation:

\n

a.js:

\n
console.log('a starting');\nexports.done = false;\nconst b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');\n
\n

b.js:

\n
console.log('b starting');\nexports.done = false;\nconst a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');\n
\n

main.js:

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

When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop, an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:

\n
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done = true, b.done = true\n
\n

Careful planning is required to allow cyclic module dependencies to work\ncorrectly within an application.

" }, { "textRaw": "File modules", "name": "File modules", "type": "misc", "desc": "

If the exact filename is not found, then Node.js will attempt to load the\nrequired filename with the added extensions: .js, .json, and finally\n.node.

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with process.dlopen().

\n

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

\n

A required module prefixed with './' is relative to the file calling\nrequire(). That is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.

\n

Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules folder.

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.

" }, { "textRaw": "Folders as modules", "name": "Folders as modules", "type": "misc", "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to those directories.\nThere are three ways in which a folder may be passed to require() as\nan argument.

\n

The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:

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

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

\n

This is the extent of the awareness of package.json files within Node.js.

\n

If there is no package.json file present in the directory, or if the\n'main' entry is missing or cannot be resolved, then Node.js\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:

\n\n

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

\n
Error: Cannot find module 'some-library'\n
" }, { "textRaw": "Loading from `node_modules` folders", "name": "Loading from `node_modules` folders", "type": "misc", "desc": "

If the module identifier passed to require() is not a\ncore module, and does not begin with '/', '../', or\n'./', then Node.js starts at the parent directory of the current module, and\nadds /node_modules, and attempts to load the module from that location.\nNode.js will not append node_modules to a path already ending in\nnode_modules.

\n

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

\n

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

\n\n

This allows programs to localize their dependencies, so that they do not\nclash.

\n

It is possible to require specific files or sub modules distributed with a\nmodule by including a path suffix after the module name. For instance\nrequire('example-module/path/to/file') would resolve path/to/file\nrelative to where example-module is located. The suffixed path follows the\nsame module resolution semantics.

" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then Node.js will search those paths for modules if they\nare not found elsewhere.

\n

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

\n

NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was defined.

\n

NODE_PATH is still supported, but is less necessary now that the Node.js\necosystem has settled on a convention for locating dependent modules.\nSometimes deployments that rely on NODE_PATH show surprising behavior\nwhen people are unaware that NODE_PATH must be set. Sometimes a\nmodule's dependencies change, causing a different version (or even a\ndifferent module) to be loaded as the NODE_PATH is searched.

\n

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

\n\n

Where $HOME is the user's home directory, and $PREFIX is the Node.js\nconfigured node_prefix.

\n

These are mostly for historic reasons.

\n

It is strongly encouraged to place dependencies in the local node_modules\nfolder. These will be loaded faster, and more reliably.

" }, { "textRaw": "The module wrapper", "name": "The module wrapper", "type": "misc", "desc": "

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

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

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

\n" } ], "modules": [ { "textRaw": "Addenda: The `.mjs` extension", "name": "addenda:_the_`.mjs`_extension", "desc": "

It is not possible to require() files that have the .mjs extension.\nAttempting to do so will throw an error. The .mjs extension is\nreserved for ECMAScript Modules which cannot be loaded via require().\nSee ECMAScript Modules for more details.

", "type": "module", "displayName": "Addenda: The `.mjs` extension" }, { "textRaw": "The module scope", "name": "the_module_scope", "vars": [ { "textRaw": "`__dirname`", "name": "`__dirname`", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "type": "var", "desc": "\n

The directory name of the current module. This is the same as the\npath.dirname() of the __filename.

\n

Example: running node example.js from /Users/mjr

\n
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
" }, { "textRaw": "`__filename`", "name": "`__filename`", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "type": "var", "desc": "\n

The file name of the current module. This is the current module file's absolute\npath with symlinks resolved.

\n

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

\n

See __dirname for the directory name of the current module.

\n

Examples:

\n

Running node example.js from /Users/mjr

\n
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
\n

Given two modules: a and b, where b is a dependency of\na and there is a directory structure of:

\n\n

References to __filename within b.js will return\n/Users/mjr/app/node_modules/b/b.js while references to __filename within\na.js will return /Users/mjr/app/a.js.

" }, { "textRaw": "`exports`", "name": "`exports`", "meta": { "added": [ "v0.1.12" ], "changes": [] }, "type": "var", "desc": "\n

A reference to the module.exports that is shorter to type.\nSee the section about the exports shortcut for details on when to use\nexports and when to use module.exports.

" }, { "textRaw": "`module`", "name": "`module`", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "type": "var", "desc": "\n

A reference to the current module, see the section about the\nmodule object. In particular, module.exports is used for defining what\na module exports and makes available through require().

" }, { "textRaw": "`require(id)`", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ], "changes": [] }, "desc": "\n

Used to import modules, JSON, and local files. Modules can be imported\nfrom node_modules. Local modules and JSON files can be imported using\na relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be\nresolved against the directory named by __dirname (if defined) or\nthe current working directory. The relative paths of POSIX style are resolved\nin an OS independent fashion, meaning that the examples above will work on\nWindows in the same way they would on Unix systems.

\n
// Importing a local module with a path relative to the `__dirname` or current\n// working directory. (On Windows, this would resolve to .\\path\\myLocalModule.)\nconst myLocalModule = require('./path/myLocalModule');\n\n// Importing a JSON file:\nconst jsonData = require('./path/filename.json');\n\n// Importing a module from node_modules or Node.js built-in module:\nconst crypto = require('crypto');\n
", "properties": [ { "textRaw": "`cache` {Object}", "type": "Object", "name": "cache", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\nThis does not apply to native addons, for which reloading will result in an\nerror.

\n

Adding or replacing entries is also possible. This cache is checked before\nnative modules and if a name matching a native module is added to the cache,\nno require call is\ngoing to receive the native module anymore. Use with care!

" }, { "textRaw": "`extensions` {Object}", "type": "Object", "name": "extensions", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.10.6" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

Instruct require on how to handle certain file extensions.

\n

Process files with the extension .sjs as .js:

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

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

\n

Avoid using require.extensions. Use could cause subtle bugs and resolving the\nextensions gets slower with each registered extension.

" }, { "textRaw": "`main` {module}", "type": "module", "name": "main", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "

The Module object representing the entry script loaded when the Node.js\nprocess launched.\nSee \"Accessing the main module\".

\n

In entry.js script:

\n
console.log(require.main);\n
\n
node entry.js\n
\n\n
Module {\n  id: '.',\n  path: '/absolute/path/to',\n  exports: {},\n  parent: null,\n  filename: '/absolute/path/to/entry.js',\n  loaded: false,\n  children: [],\n  paths:\n   [ '/absolute/path/to/node_modules',\n     '/absolute/path/node_modules',\n     '/absolute/node_modules',\n     '/node_modules' ] }\n
" } ], "methods": [ { "textRaw": "`require.resolve(request[, options])`", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": "v8.9.0", "pr-url": "https://github.com/nodejs/node/pull/16397", "description": "The `paths` option is now supported." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`request` {string} The module path to resolve.", "name": "request", "type": "string", "desc": "The module path to resolve." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`paths` {string[]} Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location.", "name": "paths", "type": "string[]", "desc": "Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location." } ] } ] } ], "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.

\n

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

", "methods": [ { "textRaw": "`require.resolve.paths(request)`", "type": "method", "name": "paths", "meta": { "added": [ "v8.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]|null}", "name": "return", "type": "string[]|null" }, "params": [ { "textRaw": "`request` {string} The module path whose lookup paths are being retrieved.", "name": "request", "type": "string", "desc": "The module path whose lookup paths are being retrieved." } ] } ], "desc": "

Returns an array containing the paths searched during resolution of request or\nnull if the request string references a core module, for example http or\nfs.

" } ] } ] } ], "type": "module", "displayName": "The module scope" }, { "textRaw": "The `Module` object", "name": "the_`module`_object", "meta": { "added": [ "v0.3.7" ], "changes": [] }, "desc": "\n

Provides general utility methods when interacting with instances of\nModule, the module variable often seen in file modules. Accessed\nvia require('module').

", "properties": [ { "textRaw": "`builtinModules` {string[]}", "type": "string[]", "name": "builtinModules", "meta": { "added": [ "v9.3.0", "v8.10.0", "v6.13.0" ], "changes": [] }, "desc": "

A list of the names of all modules provided by Node.js. Can be used to verify\nif a module is maintained by a third party or not.

\n

module in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:

\n
const builtin = require('module').builtinModules;\n
" } ], "methods": [ { "textRaw": "`module.createRequire(filename)`", "type": "method", "name": "createRequire", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {require} Require function", "name": "return", "type": "require", "desc": "Require function" }, "params": [ { "textRaw": "`filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.", "name": "filename", "type": "string|URL", "desc": "Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string." } ] } ], "desc": "
import { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n
" }, { "textRaw": "`module.createRequireFromPath(filename)`", "type": "method", "name": "createRequireFromPath", "meta": { "added": [ "v10.12.0" ], "deprecated": [ "v12.2.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Please use [`createRequire()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {require} Require function", "name": "return", "type": "require", "desc": "Require function" }, "params": [ { "textRaw": "`filename` {string} Filename to be used to construct the relative require function.", "name": "filename", "type": "string", "desc": "Filename to be used to construct the relative require function." } ] } ], "desc": "
const { createRequireFromPath } = require('module');\nconst requireUtil = createRequireFromPath('../src/utils/');\n\n// Require `../src/utils/some-tool`\nrequireUtil('./some-tool');\n
" }, { "textRaw": "`module.syncBuiltinESMExports()`", "type": "method", "name": "syncBuiltinESMExports", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The module.syncBuiltinESMExports() method updates all the live bindings for\nbuiltin ES Modules to match the properties of the CommonJS exports. It does\nnot add or remove exported names from the ES Modules.

\n
const fs = require('fs');\nconst { syncBuiltinESMExports } = require('module');\n\nfs.readFile = null;\n\ndelete fs.readFileSync;\n\nfs.newAPI = function newAPI() {\n  // ...\n};\n\nsyncBuiltinESMExports();\n\nimport('fs').then((esmFS) => {\n  assert.strictEqual(esmFS.readFile, null);\n  assert.strictEqual('readFileSync' in fs, true);\n  assert.strictEqual(esmFS.newAPI, undefined);\n});\n
" } ], "type": "module", "displayName": "The `Module` object" }, { "textRaw": "Source map v3 support", "name": "source_map_v3_support", "meta": { "added": [ "v13.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.

\n

To enable source map parsing, Node.js must be run with the flag\n--enable-source-maps, or with code coverage enabled by setting\nNODE_V8_COVERAGE=dir.

\n
const { findSourceMap, SourceMap } = require('module');\n
", "methods": [ { "textRaw": "`module.findSourceMap(path[, error])`", "type": "method", "name": "findSourceMap", "meta": { "added": [ "v13.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {module.SourceMap}", "name": "return", "type": "module.SourceMap" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" }, { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ] } ], "desc": "

path is the resolved path for the file for which a corresponding source map\nshould be fetched.

\n

The error instance should be passed as the second parameter to findSourceMap\nin exceptional flows, e.g., when an overridden\nError.prepareStackTrace(error, trace) is invoked. Modules are not added to\nthe module cache until they are successfully loaded, in these cases source maps\nwill be associated with the error instance along with the path.

" } ], "classes": [ { "textRaw": "Class: `module.SourceMap`", "type": "class", "name": "module.SourceMap", "meta": { "added": [ "v13.7.0" ], "changes": [] }, "properties": [ { "textRaw": "`payload` Returns: {Object}", "type": "Object", "name": "return", "desc": "

Getter for the payload used to construct the SourceMap instance.

" } ], "methods": [ { "textRaw": "`sourceMap.findEntry(lineNumber, columnNumber)`", "type": "method", "name": "findEntry", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`lineNumber` {number}", "name": "lineNumber", "type": "number" }, { "textRaw": "`columnNumber` {number}", "name": "columnNumber", "type": "number" } ] } ], "desc": "

Given a line number and column number in the generated source file, returns\nan object representing the position in the original file. The object returned\nconsists of the following keys:

\n" } ], "signatures": [ { "params": [ { "textRaw": "`payload` {Object}", "name": "payload", "type": "Object" } ], "desc": "

Creates a new sourceMap instance.

\n

payload is an object with keys matching the Source map v3 format:

\n" } ] } ], "type": "module", "displayName": "Source map v3 support" } ], "vars": [ { "textRaw": "The `module` object", "name": "module", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "type": "var", "desc": "\n

In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module is not actually\na global but rather local to each module.

", "properties": [ { "textRaw": "`children` {module[]}", "type": "module[]", "name": "children", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`exports` {Object}", "type": "Object", "name": "exports", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The module.exports object is created by the Module system. Sometimes this is\nnot acceptable; many want their module to be an instance of some class. To do\nthis, assign the desired export object to module.exports. Assigning\nthe desired object to exports will simply rebind the local exports variable,\nwhich is probably not what is desired.

\n

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

\n
const EventEmitter = require('events');\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(() => {\n  module.exports.emit('ready');\n}, 1000);\n
\n

Then in another file we could do:

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

Assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:

\n

x.js:

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

y.js:

\n
const x = require('./x');\nconsole.log(x.a);\n
", "modules": [ { "textRaw": "`exports` shortcut", "name": "`exports`_shortcut", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The exports variable is available within a module's file-level scope, and is\nassigned the value of module.exports before the module is evaluated.

\n

It allows a shortcut, so that module.exports.f = ... can be written more\nsuccinctly as exports.f = .... However, be aware that like any variable, if a\nnew value is assigned to exports, it is no longer bound to module.exports:

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

When the module.exports property is being completely replaced by a new\nobject, it is common to also reassign exports:

\n\n
module.exports = exports = function Constructor() {\n  // ... etc.\n};\n
\n

To illustrate the behavior, imagine this hypothetical implementation of\nrequire(), which is quite similar to what is actually done by require():

\n
function require(/* ... */) {\n  const module = { exports: {} };\n  ((module, exports) => {\n    // Module code here. In this example, define a function.\n    function someFunc() {}\n    exports = someFunc;\n    // At this point, exports is no longer a shortcut to module.exports, and\n    // this module will still export an empty default object.\n    module.exports = someFunc;\n    // At this point, the module will now export someFunc, instead of the\n    // default object.\n  })(module, module.exports);\n  return module.exports;\n}\n
", "type": "module", "displayName": "`exports` shortcut" } ] }, { "textRaw": "`filename` {string}", "type": "string", "name": "filename", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The fully resolved filename of the module.

" }, { "textRaw": "`id` {string}", "type": "string", "name": "id", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.

" }, { "textRaw": "`loaded` {boolean}", "type": "boolean", "name": "loaded", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

Whether or not the module is done loading, or is in the process of\nloading.

" }, { "textRaw": "`parent` {module | null | undefined}", "type": "module | null | undefined", "name": "parent", "meta": { "added": [ "v0.1.16" ], "deprecated": [ "v14.6.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Please use [`require.main`][] and\n[`module.children`][] instead.", "desc": "

The module that first required this one, or null if the current module is the\nentry point of the current process, or undefined if the module was loaded by\nsomething that is not a CommonJS module (E.G.: REPL or import).

" }, { "textRaw": "`path` {string}", "type": "string", "name": "path", "meta": { "added": [ "v11.14.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`paths` {string[]}", "type": "string[]", "name": "paths", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "

The search paths for the module.

" } ], "methods": [ { "textRaw": "`module.require(id)`", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any} exported module content", "name": "return", "type": "any", "desc": "exported module content" }, "params": [ { "textRaw": "`id` {string}", "name": "id", "type": "string" } ] } ], "desc": "

The module.require() method provides a way to load a module as if\nrequire() was called from the original module.

\n

In order to do this, it is necessary to get a reference to the module object.\nSince require() returns the module.exports, and the module is typically\nonly available within a specific module's code, it must be explicitly exported\nin order to be used.

" } ] } ], "type": "module", "displayName": "module" } ] }