7 Node.js has a simple module loading system. In Node.js, files and modules are
8 in one-to-one correspondence. As an example, `foo.js` loads the module
9 `circle.js` in the same directory.
11 The contents of `foo.js`:
14 const circle = require('./circle.js');
15 console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
18 The contents of `circle.js`:
23 exports.area = (r) => PI * r * r;
25 exports.circumference = (r) => 2 * PI * r;
29 The module `circle.js` has exported the functions `area()` and
30 `circumference()`. To add functions and objects to the root of your module,
31 you can add them to the special `exports` object.
33 Variables local to the module will be private, as though the module was wrapped
34 in a function. In this example the variable `PI` is private to `circle.js`.
36 If you want the root of your module's export to be a function (such as a
37 constructor) or if you want to export a complete object in one assignment
38 instead of building it one property at a time, assign it to `module.exports`
41 Below, `bar.js` makes use of the `square` module, which exports a constructor:
44 const square = require('./square.js');
45 var mySquare = square(2);
46 console.log(`The area of my square is ${mySquare.area()}`);
49 The `square` module is defined in `square.js`:
52 // assigning to exports will not modify module, must use module.exports
53 module.exports = (width) => {
55 area: () => width * width
60 The module system is implemented in the `require("module")` module.
62 ## Accessing the main module
66 When a file is run directly from Node.js, `require.main` is set to its
67 `module`. That means that you can determine whether a file has been run
71 require.main === module
74 For a file `foo.js`, this will be `true` if run via `node foo.js`, but
75 `false` if run by `require('./foo')`.
77 Because `module` provides a `filename` property (normally equivalent to
78 `__filename`), the entry point of the current application can be obtained
79 by checking `require.main.filename`.
81 ## Addenda: Package Manager Tips
85 The semantics of Node.js's `require()` function were designed to be general
86 enough to support a number of reasonable directory structures. Package manager
87 programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to
88 build native packages from Node.js modules without modification.
90 Below we give a suggested directory structure that could work:
92 Let's say that we wanted to have the folder at
93 `/usr/lib/node/<some-package>/<some-version>` hold the contents of a
94 specific version of a package.
96 Packages can depend on one another. In order to install package `foo`, you
97 may have to install a specific version of package `bar`. The `bar` package
98 may itself have dependencies, and in some cases, these dependencies may even
99 collide or form cycles.
101 Since Node.js looks up the `realpath` of any modules it loads (that is,
102 resolves symlinks), and then looks for their dependencies in the `node_modules`
103 folders as described [here](#modules_loading_from_node_modules_folders), this
104 situation is very simple to resolve with the following architecture:
106 * `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3.
107 * `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo`
109 * `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to
110 `/usr/lib/node/bar/4.3.2/`.
111 * `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages
112 that `bar` depends on.
114 Thus, even if a cycle is encountered, or if there are dependency
115 conflicts, every module will be able to get a version of its dependency
118 When the code in the `foo` package does `require('bar')`, it will get the
119 version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`.
120 Then, when the code in the `bar` package calls `require('quux')`, it'll get
121 the version that is symlinked into
122 `/usr/lib/node/bar/4.3.2/node_modules/quux`.
124 Furthermore, to make the module lookup process even more optimal, rather
125 than putting packages directly in `/usr/lib/node`, we could put them in
126 `/usr/lib/node_modules/<name>/<version>`. Then Node.js will not bother
127 looking for missing dependencies in `/usr/node_modules` or `/node_modules`.
129 In order to make modules available to the Node.js REPL, it might be useful to
130 also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment
131 variable. Since the module lookups using `node_modules` folders are all
132 relative, and based on the real path of the files making the calls to
133 `require()`, the packages themselves can be anywhere.
139 To get the exact filename that will be loaded when `require()` is called, use
140 the `require.resolve()` function.
142 Putting together all of the above, here is the high-level algorithm
143 in pseudocode of what require.resolve does:
146 require(X) from module at path Y
147 1. If X is a core module,
148 a. return the core module
150 2. If X begins with './' or '/' or '../'
151 a. LOAD_AS_FILE(Y + X)
152 b. LOAD_AS_DIRECTORY(Y + X)
153 3. LOAD_NODE_MODULES(X, dirname(Y))
157 1. If X is a file, load X as JavaScript text. STOP
158 2. If X.js is a file, load X.js as JavaScript text. STOP
159 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
160 4. If X.node is a file, load X.node as binary addon. STOP
163 1. If X/package.json is a file,
164 a. Parse X/package.json, and look for "main" field.
165 b. let M = X + (json main field)
167 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
168 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
169 4. If X/index.node is a file, load X/index.node as binary addon. STOP
171 LOAD_NODE_MODULES(X, START)
172 1. let DIRS=NODE_MODULES_PATHS(START)
173 2. for each DIR in DIRS:
174 a. LOAD_AS_FILE(DIR/X)
175 b. LOAD_AS_DIRECTORY(DIR/X)
177 NODE_MODULES_PATHS(START)
178 1. let PARTS = path split(START)
179 2. let I = count of PARTS - 1
182 a. if PARTS[I] = "node_modules" CONTINUE
183 c. DIR = path join(PARTS[0 .. I] + "node_modules")
193 Modules are cached after the first time they are loaded. This means
194 (among other things) that every call to `require('foo')` will get
195 exactly the same object returned, if it would resolve to the same file.
197 Multiple calls to `require('foo')` may not cause the module code to be
198 executed multiple times. This is an important feature. With it,
199 "partially done" objects can be returned, thus allowing transitive
200 dependencies to be loaded even when they would cause cycles.
202 If you want to have a module execute code multiple times, then export a
203 function, and call that function.
205 ### Module Caching Caveats
209 Modules are cached based on their resolved filename. Since modules may
210 resolve to a different filename based on the location of the calling
211 module (loading from `node_modules` folders), it is not a *guarantee*
212 that `require('foo')` will always return the exact same object, if it
213 would resolve to different files.
215 Additionally, on case-insensitive file systems or operating systems, different
216 resolved filenames can point to the same file, but the cache will still treat
217 them as different modules and will reload the file multiple times. For example,
218 `require('./foo')` and `require('./FOO')` return two different objects,
219 irrespective of whether or not `./foo` and `./FOO` are the same file.
225 Node.js has several modules compiled into the binary. These modules are
226 described in greater detail elsewhere in this documentation.
228 The core modules are defined within Node.js's source and are located in the
231 Core modules are always preferentially loaded if their identifier is
232 passed to `require()`. For instance, `require('http')` will always
233 return the built in HTTP module, even if there is a file by that name.
239 When there are circular `require()` calls, a module might not have finished
240 executing when it is returned.
242 Consider this situation:
247 console.log('a starting');
248 exports.done = false;
249 const b = require('./b.js');
250 console.log('in a, b.done = %j', b.done);
252 console.log('a done');
258 console.log('b starting');
259 exports.done = false;
260 const a = require('./a.js');
261 console.log('in b, a.done = %j', a.done);
263 console.log('b done');
269 console.log('main starting');
270 const a = require('./a.js');
271 const b = require('./b.js');
272 console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
275 When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that
276 point, `b.js` tries to load `a.js`. In order to prevent an infinite
277 loop, an **unfinished copy** of the `a.js` exports object is returned to the
278 `b.js` module. `b.js` then finishes loading, and its `exports` object is
279 provided to the `a.js` module.
281 By the time `main.js` has loaded both modules, they're both finished.
282 The output of this program would thus be:
293 in main, a.done=true, b.done=true
296 If you have cyclic module dependencies in your program, make sure to
303 If the exact filename is not found, then Node.js will attempt to load the
304 required filename with the added extensions: `.js`, `.json`, and finally
307 `.js` files are interpreted as JavaScript text files, and `.json` files are
308 parsed as JSON text files. `.node` files are interpreted as compiled addon
309 modules loaded with `dlopen`.
311 A required module prefixed with `'/'` is an absolute path to the file. For
312 example, `require('/home/marco/foo.js')` will load the file at
313 `/home/marco/foo.js`.
315 A required module prefixed with `'./'` is relative to the file calling
316 `require()`. That is, `circle.js` must be in the same directory as `foo.js` for
317 `require('./circle')` to find it.
319 Without a leading '/', './', or '../' to indicate a file, the module must
320 either be a core module or is loaded from a `node_modules` folder.
322 If the given path does not exist, `require()` will throw an [`Error`][] with its
323 `code` property set to `'MODULE_NOT_FOUND'`.
325 ## Folders as Modules
329 It is convenient to organize programs and libraries into self-contained
330 directories, and then provide a single entry point to that library.
331 There are three ways in which a folder may be passed to `require()` as
334 The first is to create a `package.json` file in the root of the folder,
335 which specifies a `main` module. An example package.json file might
339 { "name" : "some-library",
340 "main" : "./lib/some-library.js" }
343 If this was in a folder at `./some-library`, then
344 `require('./some-library')` would attempt to load
345 `./some-library/lib/some-library.js`.
347 This is the extent of Node.js's awareness of package.json files.
349 Note: If the file specified by the `"main"` entry of `package.json` is missing
350 and can not be resolved, Node.js will report the entire module as missing with
354 Error: Cannot find module 'some-library'
357 If there is no package.json file present in the directory, then Node.js
358 will attempt to load an `index.js` or `index.node` file out of that
359 directory. For example, if there was no package.json file in the above
360 example, then `require('./some-library')` would attempt to load:
362 * `./some-library/index.js`
363 * `./some-library/index.node`
365 ## Loading from `node_modules` Folders
369 If the module identifier passed to `require()` is not a native module,
370 and does not begin with `'/'`, `'../'`, or `'./'`, then Node.js starts at the
371 parent directory of the current module, and adds `/node_modules`, and
372 attempts to load the module from that location. Node will not append
373 `node_modules` to a path already ending in `node_modules`.
375 If it is not found there, then it moves to the parent directory, and so
376 on, until the root of the file system is reached.
378 For example, if the file at `'/home/ry/projects/foo.js'` called
379 `require('bar.js')`, then Node.js would look in the following locations, in
382 * `/home/ry/projects/node_modules/bar.js`
383 * `/home/ry/node_modules/bar.js`
384 * `/home/node_modules/bar.js`
385 * `/node_modules/bar.js`
387 This allows programs to localize their dependencies, so that they do not
390 You can require specific files or sub modules distributed with a module by
391 including a path suffix after the module name. For instance
392 `require('example-module/path/to/file')` would resolve `path/to/file`
393 relative to where `example-module` is located. The suffixed path follows the
394 same module resolution semantics.
396 ## Loading from the global folders
400 If the `NODE_PATH` environment variable is set to a colon-delimited list
401 of absolute paths, then Node.js will search those paths for modules if they
402 are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by
403 semicolons instead of colons.)
405 `NODE_PATH` was originally created to support loading modules from
406 varying paths before the current [module resolution][] algorithm was frozen.
408 `NODE_PATH` is still supported, but is less necessary now that the Node.js
409 ecosystem has settled on a convention for locating dependent modules.
410 Sometimes deployments that rely on `NODE_PATH` show surprising behavior
411 when people are unaware that `NODE_PATH` must be set. Sometimes a
412 module's dependencies change, causing a different version (or even a
413 different module) to be loaded as the `NODE_PATH` is searched.
415 Additionally, Node.js will search in the following locations:
417 * 1: `$HOME/.node_modules`
418 * 2: `$HOME/.node_libraries`
419 * 3: `$PREFIX/lib/node`
421 Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's
422 configured `node_prefix`.
424 These are mostly for historic reasons. **You are highly encouraged
425 to place your dependencies locally in `node_modules` folders.** They
426 will be loaded faster, and more reliably.
428 ## The `module` Object
435 In each module, the `module` free variable is a reference to the object
436 representing the current module. For convenience, `module.exports` is
437 also accessible via the `exports` module-global. `module` isn't actually
438 a global but rather local to each module.
444 The module objects required by this one.
450 The `module.exports` object is created by the Module system. Sometimes this is
451 not acceptable; many want their module to be an instance of some class. To do
452 this, assign the desired export object to `module.exports`. Note that assigning
453 the desired object to `exports` will simply rebind the local `exports` variable,
454 which is probably not what you want to do.
456 For example suppose we were making a module called `a.js`
459 const EventEmitter = require('events');
461 module.exports = new EventEmitter();
463 // Do some work, and after some time emit
464 // the 'ready' event from the module itself.
466 module.exports.emit('ready');
470 Then in another file we could do
473 const a = require('./a');
474 a.on('ready', () => {
475 console.log('module a is ready');
480 Note that assignment to `module.exports` must be done immediately. It cannot be
481 done in any callbacks. This does not work:
487 module.exports = { a: 'hello' };
494 const x = require('./x');
500 The `exports` variable that is available within a module starts as a reference
501 to `module.exports`. As with any variable, if you assign a new value to it, it
502 is no longer bound to the previous value.
504 To illustrate the behavior, imagine this hypothetical implementation of
508 function require(...) {
510 ((module, exports) => {
511 // Your module code here
512 exports = some_func; // re-assigns exports, exports is no longer
513 // a shortcut, and nothing is exported.
514 module.exports = some_func; // makes your module export 0
515 })(module, module.exports);
520 As a guideline, if the relationship between `exports` and `module.exports`
521 seems like magic to you, ignore `exports` and only use `module.exports`.
527 The fully resolved filename to the module.
533 The identifier for the module. Typically this is the fully resolved
540 Whether or not the module is done loading, or is in the process of
545 * {Object} Module object
547 The module that first required this one.
549 ### module.require(id)
552 * Return: {Object} `module.exports` from the resolved module
554 The `module.require` method provides a way to load a module as if
555 `require()` was called from the original module.
557 Note that in order to do this, you must get a reference to the `module`
558 object. Since `require()` returns the `module.exports`, and the `module` is
559 typically *only* available within a specific module's code, it must be
560 explicitly exported in order to be used.
562 [`Error`]: errors.html#errors_class_error
563 [module resolution]: #modules_all_together