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:
- Resolving and Loading
- Wrapping
- Execution
- Returning Exports
- 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
const mod = require( './module1.js' )
|
module1.js
console.log(require( "module" ).wrapper);
|
Output:
[
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
]
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
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
Share your thoughts in the comments
Please Login to comment...