CommonJS modules
目录
Added in: v0.10.0
CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes.
In Node.js, each file is treated as a separate module. For
example, consider a file named foo.js
:
JS
On the first line, foo.js
loads the module circle.js
that is in the same
directory as foo.js
.
Here are the contents of circle.js
:
JS
The module circle.js
has exported the functions area()
and
circumference()
. Functions and objects are added to the root of a module
by specifying additional properties on the special exports
object.
Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see module wrapper).
In this example, the variable PI
is private to circle.js
.
The module.exports
property can be assigned a new value (such as a function
or object).
Below, bar.js
makes use of the square
module, which exports a Square class:
JS
The square
module is defined in square.js
:
JS
The CommonJS module system is implemented in the module
core module.
Enabling
Node.js has two module systems: CommonJS modules and ECMAScript 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
file contains a top-level field"type"
with a value of"commonjs"
.Files with a
.js
extension when the nearest parentpackage.json
file doesn't contain a top-level field"type"
. Package authors should include the"type"
field, even in packages where all sources are CommonJS. Being explicit about thetype
of the package will make things easier for build tools and loaders to determine how the files in the package should be interpreted.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 as CommonJS modules only if they are beingrequire
d, not when used as the command-line entry point of the program).
See Determining module system for more details.
Calling require()
always use the CommonJS module loader. Calling import()
always use the ECMAScript module loader.
Accessing the main module
When a file is run directly from Node.js, require.main
is set to its
module
. That means that it is possible to determine whether a file has been
run directly by testing require.main === module
.
For a file foo.js
, this will be true
if run via node foo.js
, but
false
if run by require('./foo')
.
When the entry point is not a CommonJS module, require.main
is undefined
,
and the main module is out of reach.
Package manager tips
The semantics of the Node.js require()
function were designed to be general
enough to support reasonable directory structures. Package manager programs
such as dpkg
, rpm
, and npm
will hopefully find it possible to build
native packages from Node.js modules without modification.
Below 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 a
specific version of a package.
Packages can depend on one another. In order to install package foo
, it
may be necessary to install a specific version of package bar
. The bar
package may itself have dependencies, and in some cases, these may even collide
or form cyclic dependencies.
Because Node.js looks up the realpath
of any modules it loads (that is, it
resolves symlinks) and then looks for their dependencies in node_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
depends on./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 dependency conflicts, every module will be able to get a version of its dependency that it can use.
When the code in the foo
package does require('bar')
, it will get the
version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar
.
Then, when the code in the bar
package calls require('quux')
, it'll get
the 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, rather
than putting packages directly in /usr/lib/node
, we could put them in
/usr/lib/node_modules/<name>/<version>
. Then Node.js will not bother
looking 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
also add the /usr/lib/node_modules
folder to the $NODE_PATH
environment
variable. Since the module lookups using node_modules
folders are all
relative, and based on the real path of the files making the calls to
require()
, the packages themselves can be anywhere.
The .mjs
extension
Due to the synchronous nature of require()
, it is not possible to use it to
load ECMAScript module files. Attempting to do so will throw a
ERR_REQUIRE_ESM
error. Use import()
instead.
The .mjs
extension is reserved for ECMAScript Modules which cannot be
loaded via require()
. See Determining module system section for more info
regarding which files are parsed as ECMAScript modules.
All together
To get the exact filename that will be loaded when require()
is called, use
the require.resolve()
function.
Putting together all of the above, here is the high-level algorithm
in pseudocode of what require()
does:
TEXT
b.js
:
JS
main.js
:
JS
When main.js
loads a.js
, then a.js
in turn loads b.js
. At that
point, b.js
tries to load a.js
. In order to prevent an infinite
loop, an unfinished copy of the a.js
exports object is returned to the
b.js
module. b.js
then finishes loading, and its exports
object is
provided to the a.js
module.
By the time main.js
has loaded both modules, they're both finished.
The output of this program would thus be:
BASH
Careful planning is required to allow cyclic module dependencies to work correctly within an application.
File modules
If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: .js
, .json
, and finally
.node
. When loading a file that has a different extension (e.g. .cjs
), its
full name must be passed to require()
, including its file extension (e.g.
require('./file.cjs')
).
.json
files are parsed as JSON text files, .node
files are interpreted as
compiled addon modules loaded with process.dlopen()
. Files using any other
extension (or no extension at all) are parsed as JavaScript text files. Refer to
the Determining module system section to understand what parse goal will be
used.
A required module prefixed with '/'
is an absolute path to the file. For
example, require('/home/marco/foo.js')
will load the file at
/home/marco/foo.js
.
A required module prefixed with './'
is relative to the file calling
require()
. That is, circle.js
must be in the same directory as foo.js
for
require('./circle')
to find it.
Without a leading '/'
, './'
, or '../'
to indicate a file, the module must
either be a core module or is loaded from a node_modules
folder.
If the given path does not exist, require()
will throw a
MODULE_NOT_FOUND
error.
Folders as modules
There are three ways in which a folder may be passed to require()
as
an argument.
The first is to create a package.json
file in the root of the folder,
which specifies a main
module. An example package.json
file might
look like this:
JSON
If this was in a folder at ./some-library
, then
require('./some-library')
would attempt to load
./some-library/lib/some-library.js
.
If there is no package.json
file present in the directory, or if the
"main"
entry is missing or cannot be resolved, then Node.js
will attempt to load an index.js
or index.node
file out of that
directory. For example, if there was no package.json
file in the previous
example, then require('./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 missing with the default error:
BASH
In all three above cases, an import('./some-library')
call would result in a
ERR_UNSUPPORTED_DIR_IMPORT
error. Using package subpath exports or
subpath imports can provide the same containment organization benefits as
folders as modules, and work for both require
and import
.
Loading from node_modules
folders
If the module identifier passed to require()
is not a
core module, and does not begin with '/'
, '../'
, or
'./'
, then Node.js starts at the directory of the current module, and
adds /node_modules
, and attempts to load the module from that location.
Node.js will 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 on, until the root of the file system is reached.
For example, if the file at '/home/ry/projects/foo.js'
called
require('bar.js')
, then Node.js would look in the following locations, in
this 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 clash.
It is possible to require specific files or sub modules distributed with a
module by including a path suffix after the module name. For instance
require('example-module/path/to/file')
would resolve path/to/file
relative to where example-module
is located. The suffixed path follows the
same module resolution semantics.
Loading from the global folders
If the NODE_PATH
environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if they
are not found elsewhere.
On Windows, NODE_PATH
is delimited by semicolons (;
) instead of colons.
NODE_PATH
was originally created to support loading modules from
varying paths before the current module resolution algorithm was defined.
NODE_PATH
is still supported, but is less necessary now that the Node.js
ecosystem has settled on a convention for locating dependent modules.
Sometimes deployments that rely on NODE_PATH
show surprising behavior
when people are unaware that NODE_PATH
must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the NODE_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.js
configured node_prefix
.
These are mostly for historic reasons.
It is strongly encouraged to place dependencies in the local node_modules
folder. 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 function wrapper that looks like the following:
JS
By doing this, Node.js achieves a few things:
- It keeps top-level variables (defined with
var
,const
, orlet
) scoped to the module rather than the global object. - It helps to provide some global-looking variables that are actually specific
to the module, such as:
- The
module
andexports
objects that the implementor can use to export values from the module. - The convenience variables
__filename
and__dirname
, containing the module's absolute filename and directory path.
- The
The module scope
M __dirname
Added in: v0.1.27
The directory name of the current module. This is the same as the
path.dirname()
of the __filename
.
Example: running node example.js
from /Users/mjr
JS
M __filename
Added in: v0.0.1
The file name of the current module. This is the current module file's absolute path with symlinks resolved.
For a main program this is not necessarily the same as the file name used in the command line.
See __dirname
for the directory name of the current module.
Examples:
Running node example.js
from /Users/mjr
JS
Given two modules: a
and b
, where b
is a dependency of
a
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
/Users/mjr/app/node_modules/b/b.js
while references to __filename
within
a.js
will return /Users/mjr/app/a.js
.
M exports
Added in: v0.1.12
A reference to the module.exports
that is shorter to type.
See the section about the exports shortcut for details on when to use
exports
and when to use module.exports
.
M module
Added in: v0.1.16
A reference to the current module, see the section about the
module
object. In particular, module.exports
is used for defining what
a module exports and makes available through require()
.
M require(id)
Added in: v0.1.13
Used to import modules, JSON
, and local files. Modules can be imported
from node_modules
. Local modules and JSON files can be imported using
a relative path (e.g. ./
, ./foo
, ./bar/baz
, ../foo
) that will be
resolved against the directory named by __dirname
(if defined) or
the current working directory. The relative paths of POSIX style are resolved
in an OS independent fashion, meaning that the examples above will work on
Windows in the same way they would on Unix systems.
JS
M require.cache
Added in: v0.3.0
Modules are cached in this object when they are required. By deleting a key
value from this object, the next require
will reload the module.
This does not apply to native addons, for which reloading will result in an
error.
Adding or replacing entries is also possible. This cache is checked before
built-in modules and if a name matching a built-in module is added to the cache,
only node:
-prefixed require calls are going to receive the built-in module.
Use with care!
JS
M require.extensions
Deprecated in: v0.10.6
Instruct require
on how to handle certain file extensions.
Process files with the extension .sjs
as .js
:
JS
Deprecated. In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.
Avoid using require.extensions
. Use could cause subtle bugs and resolving the
extensions gets slower with each registered extension.
M require.main
Added in: v0.1.17
The Module
object representing the entry script loaded when the Node.js
process launched, or undefined
if the entry point of the program is not a
CommonJS module.
See "Accessing the main module".
In entry.js
script:
JS
BASH
JS
M require.resolve(request[, options])
历史
版本 | 更改 |
---|---|
v8.9.0 | The `paths` 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, 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 thenode_modules
hierarchy is checked from this location.
- Returns:
string
Use the internal require()
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, a MODULE_NOT_FOUND
error is thrown.
require.resolve.paths(request)
Added in: v8.9.0
Returns an array containing the paths searched during resolution of request
or
null
if the request
string references a core module, for example http
or
fs
.
The module
object
Added in: v0.1.16
In each module, the module
free variable is a reference to the object
representing the current module. For convenience, module.exports
is
also accessible via the exports
module-global. module
is not actually
a global but rather local to each module.
M module.children
Added in: v0.1.16
- module[]
The module objects required for the first time by this one.
M module.exports
Added in: v0.1.16
The module.exports
object is created by the Module
system. Sometimes this is
not acceptable; many want their module to be an instance of some class. To do
this, assign the desired export object to module.exports
. Assigning
the desired object to exports
will simply rebind the local exports
variable,
which is probably not what is desired.
For example, suppose we were making a module called a.js
:
JS
Then in another file we could do:
JS
Assignment to module.exports
must be done immediately. It cannot be
done in any callbacks. This does not work:
x.js
:
JS
y.js
:
JS
M exports
shortcut
Added in: v0.1.16
The exports
variable is available within a module's file-level scope, and is
assigned the value of module.exports
before the module is evaluated.
It allows a shortcut, so that module.exports.f = ...
can be written more
succinctly as exports.f = ...
. However, be aware that like any variable, if a
new value is assigned to exports
, it is no longer bound to module.exports
:
JS
When the module.exports
property is being completely replaced by a new
object, it is common to also reassign exports
:
JS
To illustrate the behavior, imagine this hypothetical implementation of
require()
, which is quite similar to what is actually done by require()
:
JS
M module.filename
Added in: v0.1.16
The fully resolved filename of the module.
M module.id
Added in: v0.1.16
The identifier for the module. Typically this is the fully resolved filename.
M module.isPreloading
Added in: v15.4.0, v14.17.0
- Type:
boolean
true
if the module is running during the Node.js preload phase.
M module.loaded
Added in: v0.1.16
Whether or not the module is done loading, or is in the process of loading.
M module.parent
Deprecated in: v14.6.0, v12.19.0
The module that first required this one, or null
if the current module is the
entry point of the current process, or undefined
if the module was loaded by
something that is not a CommonJS module (E.G.: REPL or import
).
M module.path
Added in: v11.14.0
The directory name of the module. This is usually the same as the
path.dirname()
of the module.id
.
M module.paths
Added in: v0.4.0
- string[]
The search paths for the module.
M module.require(id)
Added in: v0.5.1
The module.require()
method provides a way to load a module as if
require()
was called from the original module.
In order to do this, it is necessary to get a reference to the module
object.
Since require()
returns the module.exports
, and the module
is typically
only available within a specific module's code, it must be explicitly exported
in order to be used.
The Module
object
This section was moved to
Modules: module
core module.
Source map v3 support
This section was moved to
Modules: module
core module.