Loading modules

suggest change

If the module name is not a core module and does not start with ./, ../, or /, Node looks in node_modules in the current directory. require('myModule.js') looks for the file ./node_modules/myModule.js before it tries myModule.js.js and a directory of that name:

var myModule = require('myModule.js');

If Node fails to find the file, it will look inside the parent folder called ../node_modules/myModule.js. If it fails again, it will try the parent folder and keep descending until it reaches the root or finds the required module.

For a path such as ./lib, Node tries ./lib.js, then ./lib.json, then ./lib.node. A package name should be the folder name, not name.js.

Loading a Folder Module

You can use the path for a folder to load a module like this:

var myModule = require('./myModuleDir');

If you do so, Node will search inside that folder. Node will presume this folder is a package and will try to look for a package definition. That package definition should be a file named package.json. If that folder does not contain a package definition file named package.json, the package entry point will assume the default value of index.js, and Node will look, in this case, for a file under the path ./myModuleDir/index.js.

require does not search the global install folder. A global package is visible only if it is linked into the project or its path is listed in NODE_PATH.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents