How to work with modules and the require() function

Module

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.

The Require() function

It 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.

Exporting and exporting a module
Exporting and exporting a module

Let’s see how we can create modules and how to use them using the require() function.

How to create the module

We can create a module and add the functionality we want to perform as follows:

// sum.js
// Perform some operations
const sum = (num) => num + num
// using export keyword to export the module
module.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.

How to import the module

We'll use the require() function to import and use the module.

// main.js
// using require() function to import the module
const 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.

How to import the built-in module

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 module
const 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.

Code

Here's the complete code of how we can import our modules. Click the "Run" button to execute the code.

main.js
sum.js
// sum.js
// Perform some operations
const sum = (num) => num + num
// using export keyword to export the module
module.exports = sum

Explanation

  • 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.

Conclusion

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

Copyright ©2025 Educative, Inc. All rights reserved