aa1f0b074e504325f30c81183d6c272447279bd1
[platform/upstream/nodejs.git] / doc / api / modules.markdown
1 # Modules
2
3     Stability: 3 - Locked
4
5 <!--name=module-->
6
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.
10
11 The contents of `foo.js`:
12
13     const circle = require('./circle.js');
14     console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
15
16 The contents of `circle.js`:
17
18     const PI = Math.PI;
19
20     exports.area = function (r) {
21       return PI * r * r;
22     };
23
24     exports.circumference = function (r) {
25       return 2 * PI * r;
26     };
27
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.
31
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`.
34
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`
38 instead of `exports`.
39
40 Below, `bar.js` makes use of the `square` module, which exports a constructor:
41
42     const square = require('./square.js');
43     var mySquare = square(2);
44     console.log(`The area of my square is ${mySquare.area()}`);
45
46 The `square` module is defined in `square.js`:
47
48     // assigning to exports will not modify module, must use module.exports
49     module.exports = function(width) {
50       return {
51         area: function() {
52           return width * width;
53         }
54       };
55     }
56
57 The module system is implemented in the `require("module")` module.
58
59 ## Accessing the main module
60
61 <!-- type=misc -->
62
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
65 directly by testing
66
67     require.main === module
68
69 For a file `foo.js`, this will be `true` if run via `node foo.js`, but
70 `false` if run by `require('./foo')`.
71
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`.
75
76 ## Addenda: Package Manager Tips
77
78 <!-- type=misc -->
79
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.
84
85 Below we give a suggested directory structure that could work:
86
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.
90
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.
95
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:
100
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`
103   depends on.
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.
108
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
111 that it can use.
112
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`.
118
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`.
123
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.
129
130 ## All Together...
131
132 <!-- type=misc -->
133
134 To get the exact filename that will be loaded when `require()` is called, use
135 the `require.resolve()` function.
136
137 Putting together all of the above, here is the high-level algorithm
138 in pseudocode of what require.resolve does:
139
140     require(X) from module at path Y
141     1. If X is a core module,
142        a. return the core module
143        b. STOP
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))
148     4. THROW "not found"
149
150     LOAD_AS_FILE(X)
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
155
156     LOAD_AS_DIRECTORY(X)
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)
160        c. LOAD_AS_FILE(M)
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
164
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)
170
171     NODE_MODULES_PATHS(START)
172     1. let PARTS = path split(START)
173     2. let I = count of PARTS - 1
174     3. let DIRS = []
175     4. while I >= 0,
176        a. if PARTS[I] = "node_modules" CONTINUE
177        c. DIR = path join(PARTS[0 .. I] + "node_modules")
178        b. DIRS = DIRS + DIR
179        c. let I = I - 1
180     5. return DIRS
181
182 ## Caching
183
184 <!--type=misc-->
185
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.
189
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.
194
195 If you want to have a module execute code multiple times, then export a
196 function, and call that function.
197
198 ### Module Caching Caveats
199
200 <!--type=misc-->
201
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.
207
208 ## Core Modules
209
210 <!--type=misc-->
211
212 Node.js has several modules compiled into the binary.  These modules are
213 described in greater detail elsewhere in this documentation.
214
215 The core modules are defined within Node.js's source and are located in the
216 `lib/` folder.
217
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.
221
222 ## Cycles
223
224 <!--type=misc-->
225
226 When there are circular `require()` calls, a module might not have finished
227 executing when it is returned.
228
229 Consider this situation:
230
231 `a.js`:
232
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);
237     exports.done = true;
238     console.log('a done');
239
240 `b.js`:
241
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);
246     exports.done = true;
247     console.log('b done');
248
249 `main.js`:
250
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);
255
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.
261
262 By the time `main.js` has loaded both modules, they're both finished.
263 The output of this program would thus be:
264
265     $ node main.js
266     main starting
267     a starting
268     b starting
269     in b, a.done = false
270     b done
271     in a, b.done = true
272     a done
273     in main, a.done=true, b.done=true
274
275 If you have cyclic module dependencies in your program, make sure to
276 plan accordingly.
277
278 ## File Modules
279
280 <!--type=misc-->
281
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
284 `.node`.
285
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`.
289
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`.
293
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.
297
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.
300
301 If the given path does not exist, `require()` will throw an [`Error`][] with its
302 `code` property set to `'MODULE_NOT_FOUND'`.
303
304 ## Folders as Modules
305
306 <!--type=misc-->
307
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
311 an argument.
312
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
315 look like this:
316
317     { "name" : "some-library",
318       "main" : "./lib/some-library.js" }
319
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`.
323
324 This is the extent of Node.js's awareness of package.json files.
325
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:
330
331 * `./some-library/index.js`
332 * `./some-library/index.node`
333
334 ## Loading from `node_modules` Folders
335
336 <!--type=misc-->
337
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`.
343
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.
346
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
349 this order:
350
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`
355
356 This allows programs to localize their dependencies, so that they do not
357 clash.
358
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.
364
365 ## Loading from the global folders
366
367 <!-- type=misc -->
368
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.)
373
374 `NODE_PATH` was originally created to support loading modules from
375 varying paths before the current [module resolution][] algorithm was frozen.
376
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.
383
384 Additionally, Node.js will search in the following locations:
385
386 * 1: `$HOME/.node_modules`
387 * 2: `$HOME/.node_libraries`
388 * 3: `$PREFIX/lib/node`
389
390 Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's
391 configured `node_prefix`.
392
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.
396
397 ## The `module` Object
398
399 <!-- type=var -->
400 <!-- name=module -->
401
402 * {Object}
403
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.
408
409 ### module.children
410
411 * {Array}
412
413 The module objects required by this one.
414
415 ### module.exports
416
417 * {Object}
418
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.
424
425 For example suppose we were making a module called `a.js`
426
427     const EventEmitter = require('events');
428
429     module.exports = new EventEmitter();
430
431     // Do some work, and after some time emit
432     // the 'ready' event from the module itself.
433     setTimeout(() => {
434       module.exports.emit('ready');
435     }, 1000);
436
437 Then in another file we could do
438
439     const a = require('./a');
440     a.on('ready', () => {
441       console.log('module a is ready');
442     });
443
444
445 Note that assignment to `module.exports` must be done immediately. It cannot be
446 done in any callbacks.  This does not work:
447
448 x.js:
449
450     setTimeout(() => {
451       module.exports = { a: 'hello' };
452     }, 0);
453
454 y.js:
455
456     const x = require('./x');
457     console.log(x.a);
458
459 #### exports alias
460
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.
464
465 To illustrate the behavior, imagine this hypothetical implementation of
466 `require()`:
467
468     function require(...) {
469       // ...
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);
476       return module;
477     }
478
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`.
481
482 ### module.filename
483
484 * {String}
485
486 The fully resolved filename to the module.
487
488 ### module.id
489
490 * {String}
491
492 The identifier for the module.  Typically this is the fully resolved
493 filename.
494
495 ### module.loaded
496
497 * {Boolean}
498
499 Whether or not the module is done loading, or is in the process of
500 loading.
501
502 ### module.parent
503
504 * {Module Object}
505
506 The module that first required this one.
507
508 ### module.require(id)
509
510 * `id` {String}
511 * Return: {Object} `module.exports` from the resolved module
512
513 The `module.require` method provides a way to load a module as if
514 `require()` was called from the original module.
515
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.
520
521 [`Error`]: errors.html#errors_class_error
522 [module resolution]: #modules_all_together