Open In App

Node.js require Module

Improve
Improve
Like Article
Like
Save
Share
Report

Each JavaScript file is treated as a separate module in NodeJS. It uses commonJS module system : require(), exports and module.export.

The main object exported by require() module is a function.  When Node invokes that require() function with a file path as the function’s only argument, Node goes through the following sequence of steps:

  1. Resolving and Loading
  2. Wrapping
  3. Execution
  4. Returning Exports
  5. Caching

Let’s look at each step in more detail.

  • Resolving and Loading: In this step, Nodes decide which module to load core module or developer module or 3rd-party module using the following steps:
    • When require function receive the module name as its input, It first tries to load core module.
    • If path in require function begins with ‘./’ or ‘../’ It will try to load developer module.
    • If no file is find, it will try to find folder with index.js in it .
    • Else it will go to node_modules/ and try to load module from here .
    • If file is still not found , then an error is thrown .
  • Wrapping:once the module is loaded , the module code is wrapped in a special function which will give access to a couple of objects.
    Wrapping is done to give that loaded file a private scope or local scope. So that it can’t be accessed globally.

Folder Structure:

Example 1:

module2.js




// Caching
const mod = require('./module1.js')


module1.js




console.log(require("module").wrapper);


Output:

[
  '(function (exports, require, module, __filename, __dirname) { ',
  '\n});'
]

  • Execution: In this part, the code of the module or code inside the wrapper function run by the NodeJS runtime.
  • Returning Exports: In this part, require function return the exports of required module. These exports are stored in module.exports.

    Use module.exports to export single variable/class/function. If you want to export multiple function or variables use exports  ( exports.add = (a,b)=>a+b ).

    Returning Exports

  • Caching: At the end all modules are cached after the first time they are loaded e.g. If you require the same module multiple times, you will get the same result. So the code and modules are executed in the first call and in a subsequent call, results are retrieved from the cache.

Example 2: Lets take an example to understand caching

module1.js




console.log("Hello GEEKSFORGEEKS");
module.exports  = ()=> console.log("GeeksForGeeks is the best !!");


module2.js




// Caching
const mod = require('./module1.js');
mod();
mod();
mod();


Output:

Hello GEEKSFORGEEKS
GeeksForGeeks is the best !!
GeeksForGeeks is the best !!
GeeksForGeeks is the best !!

What happen when we require() a Module in Node,js



Last Updated : 13 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads