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`:
13 const circle = require('./circle.js');
14 console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
16 The contents of `circle.js`:
20 exports.area = function (r) {
24 exports.circumference = function (r) {
28 The module `circle.js` has exported the functions `area()` and
29 `circumference()`. To add functions and objects to the root of your module,
30 you can add them to the special `exports` object.
32 Variables local to the module will be private, as though the module was wrapped
33 in a function. In this example the variable `PI` is private to `circle.js`.
35 If you want the root of your module's export to be a function (such as a
36 constructor) or if you want to export a complete object in one assignment
37 instead of building it one property at a time, assign it to `module.exports`
40 Below, `bar.js` makes use of the `square` module, which exports a constructor:
42 const square = require('./square.js');
43 var mySquare = square(2);
44 console.log(`The area of my square is ${mySquare.area()}`);
46 The `square` module is defined in `square.js`:
48 // assigning to exports will not modify module, must use module.exports
49 module.exports = function(width) {
57 The module system is implemented in the `require("module")` module.
59 ## Accessing the main module
63 When a file is run directly from Node.js, `require.main` is set to its
64 `module`. That means that you can determine whether a file has been run
67 require.main === module
69 For a file `foo.js`, this will be `true` if run via `node foo.js`, but
70 `false` if run by `require('./foo')`.
72 Because `module` provides a `filename` property (normally equivalent to
73 `__filename`), the entry point of the current application can be obtained
74 by checking `require.main.filename`.
76 ## Addenda: Package Manager Tips
80 The semantics of Node.js's `require()` function were designed to be general
81 enough to support a number of reasonable directory structures. Package manager
82 programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to
83 build native packages from Node.js modules without modification.
85 Below we give a suggested directory structure that could work:
87 Let's say that we wanted to have the folder at
88 `/usr/lib/node/<some-package>/<some-version>` hold the contents of a
89 specific version of a package.
91 Packages can depend on one another. In order to install package `foo`, you
92 may have to install a specific version of package `bar`. The `bar` package
93 may itself have dependencies, and in some cases, these dependencies may even
94 collide or form cycles.
96 Since Node.js looks up the `realpath` of any modules it loads (that is,
97 resolves symlinks), and then looks for their dependencies in the
98 `node_modules` folders as described above, this situation is very simple to
99 resolve with the following architecture:
101 * `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3.
102 * `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo`
104 * `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to
105 `/usr/lib/node/bar/4.3.2/`.
106 * `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages
107 that `bar` depends on.
109 Thus, even if a cycle is encountered, or if there are dependency
110 conflicts, every module will be able to get a version of its dependency
113 When the code in the `foo` package does `require('bar')`, it will get the
114 version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`.
115 Then, when the code in the `bar` package calls `require('quux')`, it'll get
116 the version that is symlinked into
117 `/usr/lib/node/bar/4.3.2/node_modules/quux`.
119 Furthermore, to make the module lookup process even more optimal, rather
120 than putting packages directly in `/usr/lib/node`, we could put them in
121 `/usr/lib/node_modules/<name>/<version>`. Then Node.js will not bother
122 looking for missing dependencies in `/usr/node_modules` or `/node_modules`.
124 In order to make modules available to the Node.js REPL, it might be useful to
125 also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment
126 variable. Since the module lookups using `node_modules` folders are all
127 relative, and based on the real path of the files making the calls to
128 `require()`, the packages themselves can be anywhere.
134 To get the exact filename that will be loaded when `require()` is called, use
135 the `require.resolve()` function.
137 Putting together all of the above, here is the high-level algorithm
138 in pseudocode of what require.resolve does:
140 require(X) from module at path Y
141 1. If X is a core module,
142 a. return the core module
144 2. If X begins with './' or '/' or '../'
145 a. LOAD_AS_FILE(Y + X)
146 b. LOAD_AS_DIRECTORY(Y + X)
147 3. LOAD_NODE_MODULES(X, dirname(Y))
151 1. If X is a file, load X as JavaScript text. STOP
152 2. If X.js is a file, load X.js as JavaScript text. STOP
153 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
154 4. If X.node is a file, load X.node as binary addon. STOP
157 1. If X/package.json is a file,
158 a. Parse X/package.json, and look for "main" field.
159 b. let M = X + (json main field)
161 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
162 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
163 4. If X/index.node is a file, load X/index.node as binary addon. STOP
165 LOAD_NODE_MODULES(X, START)
166 1. let DIRS=NODE_MODULES_PATHS(START)
167 2. for each DIR in DIRS:
168 a. LOAD_AS_FILE(DIR/X)
169 b. LOAD_AS_DIRECTORY(DIR/X)
171 NODE_MODULES_PATHS(START)
172 1. let PARTS = path split(START)
173 2. let I = count of PARTS - 1
176 a. if PARTS[I] = "node_modules" CONTINUE
177 c. DIR = path join(PARTS[0 .. I] + "node_modules")
186 Modules are cached after the first time they are loaded. This means
187 (among other things) that every call to `require('foo')` will get
188 exactly the same object returned, if it would resolve to the same file.
190 Multiple calls to `require('foo')` may not cause the module code to be
191 executed multiple times. This is an important feature. With it,
192 "partially done" objects can be returned, thus allowing transitive
193 dependencies to be loaded even when they would cause cycles.
195 If you want to have a module execute code multiple times, then export a
196 function, and call that function.
198 ### Module Caching Caveats
202 Modules are cached based on their resolved filename. Since modules may
203 resolve to a different filename based on the location of the calling
204 module (loading from `node_modules` folders), it is not a *guarantee*
205 that `require('foo')` will always return the exact same object, if it
206 would resolve to different files.
212 Node.js has several modules compiled into the binary. These modules are
213 described in greater detail elsewhere in this documentation.
215 The core modules are defined within Node.js's source and are located in the
218 Core modules are always preferentially loaded if their identifier is
219 passed to `require()`. For instance, `require('http')` will always
220 return the built in HTTP module, even if there is a file by that name.
226 When there are circular `require()` calls, a module might not have finished
227 executing when it is returned.
229 Consider this situation:
233 console.log('a starting');
234 exports.done = false;
235 const b = require('./b.js');
236 console.log('in a, b.done = %j', b.done);
238 console.log('a done');
242 console.log('b starting');
243 exports.done = false;
244 const a = require('./a.js');
245 console.log('in b, a.done = %j', a.done);
247 console.log('b done');
251 console.log('main starting');
252 const a = require('./a.js');
253 const b = require('./b.js');
254 console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
256 When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that
257 point, `b.js` tries to load `a.js`. In order to prevent an infinite
258 loop, an **unfinished copy** of the `a.js` exports object is returned to the
259 `b.js` module. `b.js` then finishes loading, and its `exports` object is
260 provided to the `a.js` module.
262 By the time `main.js` has loaded both modules, they're both finished.
263 The output of this program would thus be:
273 in main, a.done=true, b.done=true
275 If you have cyclic module dependencies in your program, make sure to
282 If the exact filename is not found, then Node.js will attempt to load the
283 required filename with the added extensions: `.js`, `.json`, and finally
286 `.js` files are interpreted as JavaScript text files, and `.json` files are
287 parsed as JSON text files. `.node` files are interpreted as compiled addon
288 modules loaded with `dlopen`.
290 A required module prefixed with `'/'` is an absolute path to the file. For
291 example, `require('/home/marco/foo.js')` will load the file at
292 `/home/marco/foo.js`.
294 A required module prefixed with `'./'` is relative to the file calling
295 `require()`. That is, `circle.js` must be in the same directory as `foo.js` for
296 `require('./circle')` to find it.
298 Without a leading '/', './', or '../' to indicate a file, the module must
299 either be a core module or is loaded from a `node_modules` folder.
301 If the given path does not exist, `require()` will throw an [`Error`][] with its
302 `code` property set to `'MODULE_NOT_FOUND'`.
304 ## Folders as Modules
308 It is convenient to organize programs and libraries into self-contained
309 directories, and then provide a single entry point to that library.
310 There are three ways in which a folder may be passed to `require()` as
313 The first is to create a `package.json` file in the root of the folder,
314 which specifies a `main` module. An example package.json file might
317 { "name" : "some-library",
318 "main" : "./lib/some-library.js" }
320 If this was in a folder at `./some-library`, then
321 `require('./some-library')` would attempt to load
322 `./some-library/lib/some-library.js`.
324 This is the extent of Node.js's awareness of package.json files.
326 If there is no package.json file present in the directory, then Node.js
327 will attempt to load an `index.js` or `index.node` file out of that
328 directory. For example, if there was no package.json file in the above
329 example, then `require('./some-library')` would attempt to load:
331 * `./some-library/index.js`
332 * `./some-library/index.node`
334 ## Loading from `node_modules` Folders
338 If the module identifier passed to `require()` is not a native module,
339 and does not begin with `'/'`, `'../'`, or `'./'`, then Node.js starts at the
340 parent directory of the current module, and adds `/node_modules`, and
341 attempts to load the module from that location. Node will not append
342 `node_modules` to a path already ending in `node_modules`.
344 If it is not found there, then it moves to the parent directory, and so
345 on, until the root of the file system is reached.
347 For example, if the file at `'/home/ry/projects/foo.js'` called
348 `require('bar.js')`, then Node.js would look in the following locations, in
351 * `/home/ry/projects/node_modules/bar.js`
352 * `/home/ry/node_modules/bar.js`
353 * `/home/node_modules/bar.js`
354 * `/node_modules/bar.js`
356 This allows programs to localize their dependencies, so that they do not
359 You can require specific files or sub modules distributed with a module by
360 including a path suffix after the module name. For instance
361 `require('example-module/path/to/file')` would resolve `path/to/file`
362 relative to where `example-module` is located. The suffixed path follows the
363 same module resolution semantics.
365 ## Loading from the global folders
369 If the `NODE_PATH` environment variable is set to a colon-delimited list
370 of absolute paths, then Node.js will search those paths for modules if they
371 are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by
372 semicolons instead of colons.)
374 `NODE_PATH` was originally created to support loading modules from
375 varying paths before the current [module resolution][] algorithm was frozen.
377 `NODE_PATH` is still supported, but is less necessary now that the Node.js
378 ecosystem has settled on a convention for locating dependent modules.
379 Sometimes deployments that rely on `NODE_PATH` show surprising behavior
380 when people are unaware that `NODE_PATH` must be set. Sometimes a
381 module's dependencies change, causing a different version (or even a
382 different module) to be loaded as the `NODE_PATH` is searched.
384 Additionally, Node.js will search in the following locations:
386 * 1: `$HOME/.node_modules`
387 * 2: `$HOME/.node_libraries`
388 * 3: `$PREFIX/lib/node`
390 Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's
391 configured `node_prefix`.
393 These are mostly for historic reasons. **You are highly encouraged
394 to place your dependencies locally in `node_modules` folders.** They
395 will be loaded faster, and more reliably.
397 ## The `module` Object
404 In each module, the `module` free variable is a reference to the object
405 representing the current module. For convenience, `module.exports` is
406 also accessible via the `exports` module-global. `module` isn't actually
407 a global but rather local to each module.
413 The module objects required by this one.
419 The `module.exports` object is created by the Module system. Sometimes this is
420 not acceptable; many want their module to be an instance of some class. To do
421 this, assign the desired export object to `module.exports`. Note that assigning
422 the desired object to `exports` will simply rebind the local `exports` variable,
423 which is probably not what you want to do.
425 For example suppose we were making a module called `a.js`
427 const EventEmitter = require('events');
429 module.exports = new EventEmitter();
431 // Do some work, and after some time emit
432 // the 'ready' event from the module itself.
434 module.exports.emit('ready');
437 Then in another file we could do
439 const a = require('./a');
440 a.on('ready', () => {
441 console.log('module a is ready');
445 Note that assignment to `module.exports` must be done immediately. It cannot be
446 done in any callbacks. This does not work:
451 module.exports = { a: 'hello' };
456 const x = require('./x');
461 The `exports` variable that is available within a module starts as a reference
462 to `module.exports`. As with any variable, if you assign a new value to it, it
463 is no longer bound to the previous value.
465 To illustrate the behavior, imagine this hypothetical implementation of
468 function require(...) {
470 function (module, exports) {
471 // Your module code here
472 exports = some_func; // re-assigns exports, exports is no longer
473 // a shortcut, and nothing is exported.
474 module.exports = some_func; // makes your module export 0
475 } (module, module.exports);
479 As a guideline, if the relationship between `exports` and `module.exports`
480 seems like magic to you, ignore `exports` and only use `module.exports`.
486 The fully resolved filename to the module.
492 The identifier for the module. Typically this is the fully resolved
499 Whether or not the module is done loading, or is in the process of
506 The module that first required this one.
508 ### module.require(id)
511 * Return: {Object} `module.exports` from the resolved module
513 The `module.require` method provides a way to load a module as if
514 `require()` was called from the original module.
516 Note that in order to do this, you must get a reference to the `module`
517 object. Since `require()` returns the `module.exports`, and the `module` is
518 typically *only* available within a specific module's code, it must be
519 explicitly exported in order to be used.
521 [`Error`]: errors.html#errors_class_error
522 [module resolution]: #modules_all_together