Open In App

What is the scope of require module in Node.js ?

Whenever we have to use any feature of any other module shared by “module.exports” in our Node.js application, then we use require() method. That means we are importing those shared features into our own module and after that, we can use those features.

Now the biggest question is -what is the scope of that required module? So if we want a clear answer then it has a module scope in which it is required. This means any module imported by require function/method in a module (a javascript file) is accessible in that entire module. But if that is required inside any function of that module then it will have that function’s scope.



The require() function takes the module’s file path in the case of a user-defined module and takes the module name in the case of a third-party module. Now, whenever we try to require any module then NodeJS does the following five things:

Now let us see “How the scope of any required module works?” in the case of user-defined modules and third-party module



So first we will make two files that are “app.js” and “module.js”. “app.js” will be used to import any module and “module.js” is used for making user-defined modules.

Project Structure

User-defined Module: In this case, we will design a module by ourselves and we will export one of the functions from that module and import that using “require” into another module then that can be accessed entirely in that module.

Steps for using a user-defined module:

Example 1: In this example, we created a function in “module.js” that prints “GeeksforGeeks” in the console and exported that. Then later we imported that into our “app.js”

module.js




function printGFG() {
    console.log("GeeksforGeeks");
}
module.exports = printGFG;

app.js




const data = require("./module.js");
data();

To run the application, write the following in your terminal after going to the location of app.js and module.js

node app.js 

If you have installed “nodemon” globally then you can also write

nodemon app.js

Output:

GeeksforGeeks

Example 2: Here we will be using the “express” module. So first install that into our node application

 npm install express

app.js




const express = require("express");
const app = express();
 
app.get("/", (req, res) => {
    res.send("<h1>GeeksforGeeks</h1>");
});
 
app.listen(3000, (err) => {
    if (err) {
        console.log("Some Error Occurred");
        console.log(err);
    } else {
        console.log("Server Started on a port 3000");
    }
});

Now after writing “node app.js” in the terminal, we can get the following output at “localhost:3000” 

Output:

What’s the scope of the required (require()) modules in Node.js?

So we can clearly see that once any module gets required in any module(javascript file), then it can be accessed entirely in that module(javascript file).


Article Tags :