Import a Module
Import / include an existing module is easy. One can use a function require() to do so.
var module = require('module_name');
Which import module_name and name it as module. The module is either standard API provided by NodeJS, a module installed by npm, or simply user-defined module. Therefore, we can also use relative notation like this to import module:
var module = require("/absolute/path/to/module_name"); var module2 = require("./relative/path/to/module_name");
Where the first declaration will fetch module using absolute filepath and the second one will use path relative to current directory.
The fetched object is treated like other object. It has a name (variable name) and allocated in memory.
Modules are loaded only once per process. If you have several require calls to the same modules, Node caches the require calls if it resolves to the same files.
How Node Resolves Module Path
There are list of core modules, which Node includes in the distribution binary. It is called standard API. When we require this module, Node will just returns that module and the require() ends.
Modules with Path (Absolute or Relative)
If the module path is supplied (absolute or relative), node tries to load the modules as a file. If it does not succeed, it tries to load the module as a directory.
When loading module as a directory, it will do some procedures. If appending “/package.json” is a file, Node will try loading the package definition and look for a “main” field. It then try to load it as a file. If unsuccessful, Node will try to load it by appending “/index” to it.
Third party module is installed using NPM.
If the module path does not begin with “.” or “/” or if loading it with complete or relative paths does not work, Node tries to load the module as a module that was previously installed. It adds “/node_modules” to the current directory and tries to load the module from there. If it does not succeed it tries adding “/node_modules” to the parent directory and load the modules from there. This will be repeated until the module is found or nothing found after the root directory.