Node.js considers each file as a module. But what is significant about the module? In the browser, the window is the global object.
For example, we define the function helloNode() that can be accessed using a window.
var helloNode = function () {
return “Hello Node”;
}
window.helloNode() // O.p: Hello Node
But in a real-world application, we may have multiple files that can define functions with the same name. In that case, another function can override the original function, which may lead to an error.
So, we should avoid defining variables or functions in a global scope. Modularity comes into the picture to resolve this issue.
In OOP terminology, a module is like a class where we encapsulate business logic that can be accessed using an object.
In the code of Node, we have a concept called a module. As we discussed, every file in Node.js is considered a module—variables and functions we define in a file that are scoped to that file only. In OOP terminology, those variables and functions are private members of that file.
To make it accessible outside of that module, we must export it explicitly and make it public.
Types of modules in Node.js
There are three types of modules in Node.js
- Core Modules
Node.js comes with several built-in modules that are known as core modules. We can load these modules by using the required function.
e.g: const module = require(‘module_name’);
The required function returns a JS type, depending on what the module returns.
- Local Modules
We create modules for our project. We will create a local module in our future posts.
- Third-Party Modules.
Modules that are neither built-in nor developed locally but are available online using NPM (Node Package Manager) are known as third-party modules. These modules can be installed globally or inside the project directory by using NPM. Mongoose and Express are examples of third-party modules.
In conclusion, modules are like classes in the short term, but we need to export them to make them available for other components. We can inject those classes into our component using the required keyword, just like in the constructor. Then, we can access the module’s data, like variables and functions, by creating object variables.
That’s it for understanding the base of modules in Node.js. We will create our first local module in the next article. So stay tuned by subscribing to our newsletter. Please use the comment box for your valuable suggestions. Thank you.