{ "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
:
const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n
\nOn the first line, foo.js
loads the module circle.js
that is in the same\ndirectory as foo.js
.
Here are the contents of circle.js
:
const { PI } = Math;\n\nexports.area = (r) => PI * r ** 2;\n\nexports.circumference = (r) => 2 * PI * r;\n
\nThe 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.
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
.
The module.exports
property can be assigned a new value (such as a function\nor object).
Below, bar.js
makes use of the square
module, which exports a Square class:
const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n
\nThe square
module is defined in square.js
:
// 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
\nThe module system is implemented in the require('module')
module.
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
.
For a file foo.js
, this will be true
if run via node foo.js
, but\nfalse
if run by require('./foo')
.
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
.
The semantics of Node.js's require()
function were designed to be general\nenough to support a number of reasonable directory structures. Package manager\nprograms such as dpkg
, rpm
, and npm
will hopefully find it possible to\nbuild native packages from Node.js modules without modification.
Below we give a suggested directory structure that could work:
\nLet'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.
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.
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:
/usr/lib/node/foo/1.2.3/
- Contents of the foo
package, version 1.2.3./usr/lib/node/bar/4.3.2/
- Contents of the bar
package that foo
\ndepends on./usr/lib/node/foo/1.2.3/node_modules/bar
- Symbolic link to\n/usr/lib/node/bar/4.3.2/
./usr/lib/node/bar/4.3.2/node_modules/*
- Symbolic links to the packages\nthat bar
depends on.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.
\nWhen 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
.
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
.
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.
To get the exact filename that will be loaded when require()
is called, use\nthe require.resolve()
function.
Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve()
does:
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)\n4. LOAD_NODE_MODULES(X, dirname(Y))\n5. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text. 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. let M = X + (json main field)\n c. LOAD_AS_FILE(M)\n d. LOAD_INDEX(M)\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_AS_FILE(DIR/X)\n b. 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 = []\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
\n"
},
{
"textRaw": "Caching",
"name": "Caching",
"type": "misc",
"desc": "Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo')
will get\nexactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo')
may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.
To have a module execute code multiple times, export a function, and call\nthat function.
\n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules
folders), it is not a guarantee\nthat require('foo')
will always return the exact same object, if it\nwould resolve to different files.
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.
Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.
\nThe core modules are defined within Node.js's source and are located in the\nlib/
folder.
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.
When there are circular require()
calls, a module might not have finished\nexecuting when it is returned.
Consider this situation:
\na.js
:
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
\nb.js
:
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
\nmain.js
:
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
\nWhen 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.
By the time main.js
has loaded both modules, they're both finished.\nThe output of this program would thus be:
$ 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
\nCareful planning is required to allow cyclic module dependencies to work\ncorrectly within an application.
\n" }, { "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
.
.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 dlopen
.
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
.
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.
Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules
folder.
If the given path does not exist, require()
will throw an Error
with its\ncode
property set to 'MODULE_NOT_FOUND'
.
It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require()
as\nan argument.
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:
{ "name" : "some-library",\n "main" : "./lib/some-library.js" }\n
\nIf this was in a folder at ./some-library
, then\nrequire('./some-library')
would attempt to load\n./some-library/lib/some-library.js
.
This is the extent of Node.js's awareness of package.json files.
\nNote: If the file specified by the 'main'
entry of package.json
is\nmissing and can not be resolved, Node.js will report the entire module as\nmissing with the default error:
Error: Cannot find module 'some-library'\n
\nIf there is no package.json file present in the directory, 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:
./some-library/index.js
./some-library/index.node
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. Node\nwill not append node_modules
to a path already ending in node_modules
.
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.
\nFor 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:
/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 not\nclash.
\nIt 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.
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.
Note: On Windows, NODE_PATH
is delimited by semicolons instead of colons.
NODE_PATH
was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was frozen.
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.
Additionally, Node.js will search in the following locations:
\n$HOME/.node_modules
$HOME/.node_libraries
$PREFIX/lib/node
Where $HOME
is the user's home directory, and $PREFIX
is Node.js's\nconfigured node_prefix
.
These are mostly for historic reasons.
\nNote: It is strongly encouraged to place dependencies in the local\nnode_modules
folder. These will be loaded faster, and more reliably.
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
\nBy doing this, Node.js achieves a few things:
\nvar
, const
or let
) scoped to\nthe module rather than the global object.module
and exports
objects that the implementor can use to export\nvalues from the module.__filename
and __dirname
, containing the\nmodule's absolute filename and directory path.The directory name of the current module. This is the same as the\npath.dirname()
of the __filename
.
Example: running node example.js
from /Users/mjr
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
\n"
},
{
"textRaw": "\\_\\_filename",
"name": "\\_\\_filename",
"meta": {
"added": [
"v0.0.1"
],
"changes": []
},
"type": "var",
"desc": "The file name of the current module. This is the resolved absolute path of the\ncurrent module file.
\nFor a main program this is not necessarily the same as the file name used in the\ncommand line.
\nSee __dirname
for the directory name of the current module.
Examples:
\nRunning node example.js
from /Users/mjr
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
\nGiven two modules: a
and b
, where b
is a dependency of\na
and there is a directory structure of:
/Users/mjr/app/a.js
/Users/mjr/app/node_modules/b/b.js
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
.
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
.
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()
.
To require modules.
\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. Note that\nthis does not apply to native addons, for which reloading will result in an\nError.
Instruct require
on how to handle certain file extensions.
Process files with the extension .sjs
as .js
:
require.extensions['.sjs'] = require.extensions['.js'];\n
\nDeprecated In the past, this list has been used to load\nnon-JavaScript modules into Node.js by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node.js program, or compiling them to\nJavaScript ahead of time.
\nSince the module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.
\nNote that the number of file system operations that the module system\nhas to perform in order to resolve a require(...)
statement to a\nfilename scales linearly with the number of registered extensions.
In other words, adding extensions slows down the module loader and\nshould be discouraged.
\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} ", "options": [ { "textRaw": "`paths` {Array} Paths to resolve module location from. If present, these paths are used instead of the default resolution paths. Note that 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": "Array", "desc": "Paths to resolve module location from. If present, these paths are used instead of the default resolution paths. Note that 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": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "request" }, { "name": "options", "optional": true } ] } ], "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.
request
{string} The module path whose lookup paths are being retrieved.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
.
Provides general utility methods when interacting with instances of\nModule
— the module
variable often seen in file modules. Accessed\nvia require('module')
.
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 module or not.
\n" } ], "type": "module", "displayName": "The `Module` Object" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "type": "var", "desc": "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.
The module objects required by this one.
\n" }, { "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
. Note that assigning\nthe desired object to exports
will simply rebind the local exports
variable,\nwhich is probably not what is desired.
For example suppose we were making a module called a.js
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
\nThen in another file we could do
\nconst a = require('./a');\na.on('ready', () => {\n console.log('module a is ready');\n});\n
\nNote that assignment to module.exports
must be done immediately. It cannot be\ndone in any callbacks. This does not work:
x.js:
\nsetTimeout(() => {\n module.exports = { a: 'hello' };\n}, 0);\n
\ny.js:
\nconst x = require('./x');\nconsole.log(x.a);\n
\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.
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
:
module.exports.hello = true; // Exported from require of module\nexports = { hello: false }; // Not exported, only available in the module\n
\nWhen the module.exports
property is being completely replaced by a new\nobject, it is common to also reassign exports
, for example:
module.exports = exports = function Constructor() {\n // ... etc.\n};\n
\nTo illustrate the behavior, imagine this hypothetical implementation of\nrequire()
, which is quite similar to what is actually done by require()
:
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
\n",
"type": "module",
"displayName": "exports shortcut"
}
]
},
{
"textRaw": "`filename` {string} ",
"type": "string",
"name": "filename",
"meta": {
"added": [
"v0.1.16"
],
"changes": []
},
"desc": "The fully resolved filename to the module.
\n" }, { "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.
\n" }, { "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.
\n" }, { "textRaw": "`parent` {Object} Module object ", "type": "Object", "name": "parent", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "The module that first required this one.
\n", "shortDesc": "Module object" }, { "textRaw": "`paths` {string[]} ", "type": "string[]", "name": "paths", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "The search paths for the module.
\n" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {string} ", "name": "id", "type": "string" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The module.require
method provides a way to load a module as if\nrequire()
was called from the original module.
Note: In order to do this, it is necessary to get a reference to the\nmodule
object. Since require()
returns the module.exports
, and the\nmodule
is typically only available within a specific module's code, it must\nbe explicitly exported in order to be used.