{ "source": "doc/api/modules.markdown", "modules": [ { "textRaw": "Modules", "name": "module", "stability": 5, "stabilityText": "Locked", "desc": "

Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

\n

The contents of foo.js:\n\n

\n
var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
\n

The contents of circle.js:\n\n

\n
var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
\n

The module circle.js has exported the functions area() and\ncircumference(). To add functions and objects to the root of your module,\nyou can add them to the special exports object.\n\n

\n

Variables local to the module will be private, as though the module was wrapped\nin a function. In this example the variable PI is private to circle.js.\n\n

\n

If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports\ninstead of exports.\n\n

\n

Below, bar.js makes use of the square module, which exports a constructor:\n\n

\n
var square = require('./square.js');\nvar mySquare = square(2);\nconsole.log('The area of my square is ' + mySquare.area());
\n

The square module is defined in square.js:\n\n

\n
// assigning to exports will not modify module, must use module.exports\nmodule.exports = function(width) {\n  return {\n    area: function() {\n      return width * width;\n    }\n  };\n}
\n

The module system is implemented in the require("module") module.\n\n

\n", "miscs": [ { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

\n

Consider this situation:\n\n

\n

a.js:\n\n

\n
console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
\n

b.js:\n\n

\n
console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
\n

main.js:\n\n

\n
console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
\n

When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

\n
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
\n

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

\n" }, { "textRaw": "Core Modules", "name": "Core Modules", "type": "misc", "desc": "

Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

\n

The core modules are defined in node's source in the lib/ folder.\n\n

\n

Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

\n" }, { "textRaw": "File Modules", "name": "File Modules", "type": "misc", "desc": "

If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

\n

A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

\n

A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

\n

Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

\n" }, { "textRaw": "Loading from `node_modules` Folders", "name": "Loading from `node_modules` Folders", "type": "misc", "desc": "

If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

\n

If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.\n\n

\n

For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

\n\n

This allows programs to localize their dependencies, so that they do not\nclash.\n\n

\n" }, { "textRaw": "Folders as Modules", "name": "Folders as Modules", "type": "misc", "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

\n

The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

\n
{ "name" : "some-library",\n  "main" : "./lib/some-library.js" }
\n

If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

\n

This is the extent of Node's awareness of package.json files.\n\n

\n

If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

\n\n" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

\n

Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

\n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "

Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

\n" } ] }, { "textRaw": "All Together...", "name": "All Together...", "type": "misc", "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.json is a file, parse X.json to a JavaScript Object.  STOP\n4. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n4. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = []\n4. while I >= 0,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n5. return DIRS
\n" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

\n

Additionally, node will search in the following locations:\n\n

\n\n

Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

\n

These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

\n" }, { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

\n
require.main === module
\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

\n" }, { "textRaw": "Addenda: Package Manager Tips", "name": "Addenda: Package Manager Tips", "type": "misc", "desc": "

The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

\n

Below we give a suggested directory structure that could work:\n\n

\n

Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

\n

Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

\n

Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

\n\n

Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

\n

When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

\n

Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

\n

In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n

\n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "type": "var", "desc": "

In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module isn't actually\na global but rather local to each module.\n\n

\n", "properties": [ { "textRaw": "`exports` {Object} ", "name": "exports", "desc": "

The module.exports object is created by the Module system. Sometimes this is not\nacceptable; many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. Note that assigning the\ndesired object to exports will simply rebind the local exports variable,\nwhich is probably not what you want to do.\n\n

\n

For example suppose we were making a module called a.js\n\n

\n
var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
\n

Then in another file we could do\n\n

\n
var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
\n

Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

\n

x.js:\n\n

\n
setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
\n

y.js:\n\n

\n
var x = require('./x');\nconsole.log(x.a);
\n", "modules": [ { "textRaw": "exports alias", "name": "exports_alias", "desc": "

The exports variable that is available within a module starts as a reference\nto module.exports. As with any variable, if you assign a new value to it, it\nis no longer bound to the previous value.\n\n

\n

To illustrate the behaviour, imagine this hypothetical implementation of\nrequire():\n\n

\n
function require(...) {\n  // ...\n  function (module, exports) {\n    // Your module code here\n    exports = some_func;        // re-assigns exports, exports is no longer\n                                // a shortcut, and nothing is exported.\n    module.exports = some_func; // makes your module export 0\n  } (module, module.exports);\n  return module;\n}
\n

As a guideline, if the relationship between exports and module.exports\nseems like magic to you, ignore exports and only use module.exports.\n\n

\n", "type": "module", "displayName": "exports alias" } ] }, { "textRaw": "`id` {String} ", "name": "id", "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

\n" }, { "textRaw": "`filename` {String} ", "name": "filename", "desc": "

The fully resolved filename to the module.\n\n\n

\n" }, { "textRaw": "`loaded` {Boolean} ", "name": "loaded", "desc": "

Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

\n" }, { "textRaw": "`parent` {Module Object} ", "name": "parent", "desc": "

The module that required this one.\n\n\n

\n" }, { "textRaw": "`children` {Array} ", "name": "children", "desc": "

The module objects required by this one.\n\n\n\n

\n" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "signatures": [ { "return": { "textRaw": "Return: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {String} ", "name": "id", "type": "String" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "

The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

\n

Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the module.exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

\n" } ] } ], "type": "module", "displayName": "module" } ] }