doc: `require` behavior on case-insensitive systems
[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 ```js
14 const circle = require('./circle.js');
15 console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
16 ```
17
18 The contents of `circle.js`:
19
20 ```js
21 const PI = Math.PI;
22
23 exports.area = (r) => PI * r * r;
24
25 exports.circumference = (r) => 2 * PI * r;
26
27 ```
28
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.
32
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`.
35
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`
39 instead of `exports`.
40
41 Below, `bar.js` makes use of the `square` module, which exports a constructor:
42
43 ```js
44 const square = require('./square.js');
45 var mySquare = square(2);
46 console.log(`The area of my square is ${mySquare.area()}`);
47 ```
48
49 The `square` module is defined in `square.js`:
50
51 ```js
52 // assigning to exports will not modify module, must use module.exports
53 module.exports = (width) => {
54   return {
55     area: () => width * width
56   };
57 }
58 ```
59
60 The module system is implemented in the `require("module")` module.
61
62 ## Accessing the main module
63
64 <!-- type=misc -->
65
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
68 directly by testing
69
70 ```js
71 require.main === module
72 ```
73
74 For a file `foo.js`, this will be `true` if run via `node foo.js`, but
75 `false` if run by `require('./foo')`.
76
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`.
80
81 ## Addenda: Package Manager Tips
82
83 <!-- type=misc -->
84
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.
89
90 Below we give a suggested directory structure that could work:
91
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.
95
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.
100
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:
105
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`
108   depends on.
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.
113
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
116 that it can use.
117
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`.
123
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`.
128
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.
134
135 ## All Together...
136
137 <!-- type=misc -->
138
139 To get the exact filename that will be loaded when `require()` is called, use
140 the `require.resolve()` function.
141
142 Putting together all of the above, here is the high-level algorithm
143 in pseudocode of what require.resolve does:
144
145 ```
146 require(X) from module at path Y
147 1. If X is a core module,
148    a. return the core module
149    b. STOP
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))
154 4. THROW "not found"
155
156 LOAD_AS_FILE(X)
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
161
162 LOAD_AS_DIRECTORY(X)
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)
166    c. LOAD_AS_FILE(M)
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
170
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)
176
177 NODE_MODULES_PATHS(START)
178 1. let PARTS = path split(START)
179 2. let I = count of PARTS - 1
180 3. let DIRS = []
181 4. while I >= 0,
182    a. if PARTS[I] = "node_modules" CONTINUE
183    c. DIR = path join(PARTS[0 .. I] + "node_modules")
184    b. DIRS = DIRS + DIR
185    c. let I = I - 1
186 5. return DIRS
187 ```
188
189 ## Caching
190
191 <!--type=misc-->
192
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.
196
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.
201
202 If you want to have a module execute code multiple times, then export a
203 function, and call that function.
204
205 ### Module Caching Caveats
206
207 <!--type=misc-->
208
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.
214
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.
220
221 ## Core Modules
222
223 <!--type=misc-->
224
225 Node.js has several modules compiled into the binary.  These modules are
226 described in greater detail elsewhere in this documentation.
227
228 The core modules are defined within Node.js's source and are located in the
229 `lib/` folder.
230
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.
234
235 ## Cycles
236
237 <!--type=misc-->
238
239 When there are circular `require()` calls, a module might not have finished
240 executing when it is returned.
241
242 Consider this situation:
243
244 `a.js`:
245
246 ```
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);
251 exports.done = true;
252 console.log('a done');
253 ```
254
255 `b.js`:
256
257 ```
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);
262 exports.done = true;
263 console.log('b done');
264 ```
265
266 `main.js`:
267
268 ```
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);
273 ```
274
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.
280
281 By the time `main.js` has loaded both modules, they're both finished.
282 The output of this program would thus be:
283
284 ```
285 $ node main.js
286 main starting
287 a starting
288 b starting
289 in b, a.done = false
290 b done
291 in a, b.done = true
292 a done
293 in main, a.done=true, b.done=true
294 ```
295
296 If you have cyclic module dependencies in your program, make sure to
297 plan accordingly.
298
299 ## File Modules
300
301 <!--type=misc-->
302
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
305 `.node`.
306
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`.
310
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`.
314
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.
318
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.
321
322 If the given path does not exist, `require()` will throw an [`Error`][] with its
323 `code` property set to `'MODULE_NOT_FOUND'`.
324
325 ## Folders as Modules
326
327 <!--type=misc-->
328
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
332 an argument.
333
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
336 look like this:
337
338 ```
339 { "name" : "some-library",
340   "main" : "./lib/some-library.js" }
341 ```
342
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`.
346
347 This is the extent of Node.js's awareness of package.json files.
348
349 If there is no package.json file present in the directory, then Node.js
350 will attempt to load an `index.js` or `index.node` file out of that
351 directory.  For example, if there was no package.json file in the above
352 example, then `require('./some-library')` would attempt to load:
353
354 * `./some-library/index.js`
355 * `./some-library/index.node`
356
357 ## Loading from `node_modules` Folders
358
359 <!--type=misc-->
360
361 If the module identifier passed to `require()` is not a native module,
362 and does not begin with `'/'`, `'../'`, or `'./'`, then Node.js starts at the
363 parent directory of the current module, and adds `/node_modules`, and
364 attempts to load the module from that location. Node will not append
365 `node_modules` to a path already ending in `node_modules`.
366
367 If it is not found there, then it moves to the parent directory, and so
368 on, until the root of the file system is reached.
369
370 For example, if the file at `'/home/ry/projects/foo.js'` called
371 `require('bar.js')`, then Node.js would look in the following locations, in
372 this order:
373
374 * `/home/ry/projects/node_modules/bar.js`
375 * `/home/ry/node_modules/bar.js`
376 * `/home/node_modules/bar.js`
377 * `/node_modules/bar.js`
378
379 This allows programs to localize their dependencies, so that they do not
380 clash.
381
382 You can require specific files or sub modules distributed with a module by
383 including a path suffix after the module name. For instance
384 `require('example-module/path/to/file')` would resolve `path/to/file`
385 relative to where `example-module` is located. The suffixed path follows the
386 same module resolution semantics.
387
388 ## Loading from the global folders
389
390 <!-- type=misc -->
391
392 If the `NODE_PATH` environment variable is set to a colon-delimited list
393 of absolute paths, then Node.js will search those paths for modules if they
394 are not found elsewhere.  (Note: On Windows, `NODE_PATH` is delimited by
395 semicolons instead of colons.)
396
397 `NODE_PATH` was originally created to support loading modules from
398 varying paths before the current [module resolution][] algorithm was frozen.
399
400 `NODE_PATH` is still supported, but is less necessary now that the Node.js
401 ecosystem has settled on a convention for locating dependent modules.
402 Sometimes deployments that rely on `NODE_PATH` show surprising behavior
403 when people are unaware that `NODE_PATH` must be set.  Sometimes a
404 module's dependencies change, causing a different version (or even a
405 different module) to be loaded as the `NODE_PATH` is searched.
406
407 Additionally, Node.js will search in the following locations:
408
409 * 1: `$HOME/.node_modules`
410 * 2: `$HOME/.node_libraries`
411 * 3: `$PREFIX/lib/node`
412
413 Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's
414 configured `node_prefix`.
415
416 These are mostly for historic reasons.  **You are highly encouraged
417 to place your dependencies locally in `node_modules` folders.**  They
418 will be loaded faster, and more reliably.
419
420 ## The `module` Object
421
422 <!-- type=var -->
423 <!-- name=module -->
424
425 * {Object}
426
427 In each module, the `module` free variable is a reference to the object
428 representing the current module.  For convenience, `module.exports` is
429 also accessible via the `exports` module-global. `module` isn't actually
430 a global but rather local to each module.
431
432 ### module.children
433
434 * {Array}
435
436 The module objects required by this one.
437
438 ### module.exports
439
440 * {Object}
441
442 The `module.exports` object is created by the Module system. Sometimes this is
443 not acceptable; many want their module to be an instance of some class. To do
444 this, assign the desired export object to `module.exports`. Note that assigning
445 the desired object to `exports` will simply rebind the local `exports` variable,
446 which is probably not what you want to do.
447
448 For example suppose we were making a module called `a.js`
449
450 ```js
451 const EventEmitter = require('events');
452
453 module.exports = new EventEmitter();
454
455 // Do some work, and after some time emit
456 // the 'ready' event from the module itself.
457 setTimeout(() => {
458   module.exports.emit('ready');
459 }, 1000);
460 ```
461
462 Then in another file we could do
463
464 ```js
465 const a = require('./a');
466 a.on('ready', () => {
467   console.log('module a is ready');
468 });
469 ```
470
471
472 Note that assignment to `module.exports` must be done immediately. It cannot be
473 done in any callbacks.  This does not work:
474
475 x.js:
476
477 ```js
478 setTimeout(() => {
479   module.exports = { a: 'hello' };
480 }, 0);
481 ```
482
483 y.js:
484
485 ```js
486 const x = require('./x');
487 console.log(x.a);
488 ```
489
490 #### exports alias
491
492 The `exports` variable that is available within a module starts as a reference
493 to `module.exports`. As with any variable, if you assign a new value to it, it
494 is no longer bound to the previous value.
495
496 To illustrate the behavior, imagine this hypothetical implementation of
497 `require()`:
498
499 ```js
500 function require(...) {
501   // ...
502   ((module, exports) => {
503     // Your module code here
504     exports = some_func;        // re-assigns exports, exports is no longer
505                                 // a shortcut, and nothing is exported.
506     module.exports = some_func; // makes your module export 0
507   })(module, module.exports);
508   return module;
509 }
510 ```
511
512 As a guideline, if the relationship between `exports` and `module.exports`
513 seems like magic to you, ignore `exports` and only use `module.exports`.
514
515 ### module.filename
516
517 * {String}
518
519 The fully resolved filename to the module.
520
521 ### module.id
522
523 * {String}
524
525 The identifier for the module.  Typically this is the fully resolved
526 filename.
527
528 ### module.loaded
529
530 * {Boolean}
531
532 Whether or not the module is done loading, or is in the process of
533 loading.
534
535 ### module.parent
536
537 * {Object} Module object
538
539 The module that first required this one.
540
541 ### module.require(id)
542
543 * `id` {String}
544 * Return: {Object} `module.exports` from the resolved module
545
546 The `module.require` method provides a way to load a module as if
547 `require()` was called from the original module.
548
549 Note that in order to do this, you must get a reference to the `module`
550 object.  Since `require()` returns the `module.exports`, and the `module` is
551 typically *only* available within a specific module's code, it must be
552 explicitly exported in order to be used.
553
554 [`Error`]: errors.html#errors_class_error
555 [module resolution]: #modules_all_together