Open In App

Node.js require Module

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.

Folder Structure:



Example 1:




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




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

Output:

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

Example 2: Lets take an example to understand caching




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




// 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


Article Tags :