A module is a functionality written independently as a separate unit but does not function independently. We break our application into multiple small parts in the form of modules to make it simple and reusable. We can have multiple modules and use them multiple times in our application. There are several advantages of using modules, as listed below:
It provides code reusability.
It has better code organization.
It offers encapsulation.
It offers dependency management.
It offers improved testing and debugging capabilities.
Require()
functionIt is a built-in function in Node.js to import the modules. With the help of this function, we can include built-in modules or those created by us in our application.
Let’s see how we can create modules and how to use them using the require()
function.
We can create a module and add the functionality we want to perform as follows:
// sum.js// Perform some operationsconst sum = (num) => num + num// using export keyword to export the modulemodule.exports = sum
We created a module that takes a number and returns it's sum. We used the module.exports
to make sure our module sum.js
is accessible when we import it into our application.
We'll use the require()
function to import and use the module.
// main.js// using require() function to import the moduleconst square = require('./sum')console.log(square(2))
We used require()
to import and use our module sum.js
. Notice that we must set the relative path of the module we want to import.
As mentioned earlier, we can import built-in modules as well by using the require()
function.
// main.js// using require() function to import// built-in moduleconst http = require('http')const express = require('express')
We imported built-in modules using the require()
function.
Note: For built-in modules, we don't need to set any path.
Here's the complete code of how we can import our modules. Click the "Run" button to execute the code.
// sum.js// Perform some operationsconst sum = (num) => num + num// using export keyword to export the modulemodule.exports = sum
main.js
:
We imported our module sum.js
and displayed the output on the console.
sum.js
:
We created a function that adds a number to itself and returns the result. We exported this function using the module.exports
.
With the help of modules and the require()
function, we can organize our code in a clean, easy-to-understand, and reusable way.
Free Resources