{ "source": "doc/api/modules.md", "modules": [ { "textRaw": "Modules", "name": "module", "stability": 2, "stabilityText": "Stable", "desc": "
Node.js has a simple module loading system. In Node.js, files and modules\nare in one-to-one correspondence (each file is treated as a separate module).
\nAs an example, 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 * r;\n\nexports.circumference = (r) => 2 * PI * r;\n
\nThe module circle.js
has exported the functions area()
and\ncircumference()
. To add functions and objects to the root of your module,\nyou can add them to 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
.
If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports
\ninstead of exports
.
Below, bar.js
makes use of the square
module, which exports a constructor:
const square = require('./square.js');\nconst mySquare = square(2);\nconsole.log(`The area of my square 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 = (width) => {\n return {\n area: () => width * width\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 you can determine whether a file has been run\ndirectly by testing
require.main === module\n
\nFor 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
, you\nmay have to install a specific version of package bar
. The bar
package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.
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.
If you want to have a module execute code multiple times, then export a\nfunction, and call that 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
\nIf you have cyclic module dependencies in your program, make sure to\nplan accordingly.
\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 missing\nand can not be resolved, Node.js will report the entire module as missing with\nthe 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.
\nYou can require specific files or sub modules distributed with a module by\nincluding 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\nsemicolons 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. You are highly encouraged\nto place your dependencies locally in node_modules
folders. They\nwill 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// Your 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.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" ] }, "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 you want to do.
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"
]
},
"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
\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 // Your 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"
]
},
"desc": "The fully resolved filename to the module.
\n" }, { "textRaw": "`id` {String} ", "type": "String", "name": "id", "meta": { "added": [ "v0.1.16" ] }, "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" ] }, "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" ] }, "desc": "The module that first required this one.
\n", "shortDesc": "Module object" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ] }, "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 that in order to do this, you must get a reference to the module
\nobject. Since require()
returns the module.exports
, and the module
is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.