Basics of require and module in Nodejs
Node.js
usages require as one of the global modules to manage the module dependencies. You can require any module in Nodejs by a simple line of code.
const myApp = require('path/to/myApp')
Node.js
modules and files have the one-to-one relation, every single file is treated as the separate module. Node.js usages a function wrapper to before executing the module’s code.
(function(exports, require, module, __filename, __dirname){
// and actual module code lives here
})
By doing this Node.js
keeps the top-level variable defined in the module within the scope of the module rather than the global scope.
- to get more details about the module wrapper go here
Wherever we do require('findAModule')
, Node.js
will look for either findAModule.js or findAModule dir with index.js (findAModule/index.js)
in all the paths added to the module.paths array.
Here are the example values for module.paths
in my development machine
[
'/Users/rakeshverma/repl/node_modules',
'/Users/rakeshverma/node_modules',
'/Users/node_modules',
'/node_modules',
'/Users/rakeshverma/.node_modules',
'/Users/rakeshverma/.node_libraries',
'/usr/local/lib/node'
]
So these are the places where Node.js
will look for the modules for the require call on my development machine. Yours could vary based on your operating system.
Below are a couple of simple examples of how to require work to find the given module.
1.
require('findAModule') // where 'findAModule' could be a file or directory
// Node.js will look for the files
> findAModule / findAModule.js / findAModule.json / findAModule.node
// or For directory
> findAModule/index / findAModule/index.js / findAModule/index.json / findAModule/index.node
Based on file extension Node.js
load the content for without extension files it loads the content as JavaScript text, .js
extension file loads the content as JavaScript text, .json
extension file loads the content as JavaScript
object, .node
extension file loads as binary addon
require('findAModule') // where 'findAModule' is a directory and It has package.json ('findAModule/package.json')
Here Node.js
will first parse the package.json
file and look for the 'main'
file and repeat the step 1 require procedure based on the 'main'
field value.
We can change the Node.js
default behavior for the require
of the folder (by default folder index.js
file to load) by changing the package.json
'main'
filed value to look for the specific file name.
// package.json
{
"name" : "foo",
"version" : "0.3",
"description" : "A packaged foo for bar and foobar",
"main" : "foo.js"
}