Creating Custom Modules in Node.js
Learn how to create your own reusable modules in Node.js. Understand how to separate program logic into different files, export functions and variables, import modules, and build a practical application using custom modules.
1. What Is a Custom Module?
A custom module is a JavaScript file created by a developer to perform a particular task in an application. Instead of writing all the program logic in one file, we can divide the application into smaller files called modules.
For example, a student management application may contain separate files for student details, marks calculation, and the main program. Each file can handle its own responsibility.
Node.js allows us to create custom modules and reuse their
functionality in other files. We can use CommonJS syntax with
module.exports and require(), or ES
Module syntax with export and import.
Example
function add(a, b) {
return a + b;
}
module.exports = add;
In this example, we created our own function named
add(). The statement module.exports = add
makes the function available to another CommonJS module.
2. Why Do We Create Custom Modules?
As an application grows, writing every function in one file makes the program difficult to understand and maintain. Custom modules help us organize the code properly.
- Code Reusability: Write a function once and use it in multiple files.
- Code Organization: Keep related functions and logic together.
- Easy Maintenance: Update a particular feature in its own file.
- Readability: Keep the main application file shorter and easier to understand.
- Separation of Responsibilities: Keep calculation, validation, and data-handling logic separate.
- Testing: Test individual functions and modules independently.
3. Custom Module Working Diagram
A custom module is created in one file, exported, and then imported into another file. The main program can call the imported function and use its result.
Step 1: Create a Module
Create a file such as math.js and define
reusable functions.
Step 2: Export Functionality
Use module.exports to expose the function.
Step 3: Import the Module
Use require("./math") in another file.
Step 4: Use the Function
Call the imported function and display its result.
4. Creating Your First Custom Module
Let us create a simple custom module that performs addition.
We will use two JavaScript files: math.js and
app.js.
Step 1: Create the Project Folder
Create a folder named CustomModuleExample.
Inside this folder, create the following two files.
CustomModuleExample/
math.js
app.js
Step 2: Write the Custom Module
Open math.js and write the following program.
function add(a, b) {
return a + b;
}
module.exports = add;
Explanation:
-
function add(a, b)defines a function with two parameters. -
return a + breturns the sum of the two values. -
module.exports = addexports the function so another CommonJS file can use it.
Step 3: Import the Custom Module
Open app.js. Use require() to load
the exported function.
const add = require("./math");
const result = add(10, 20);
console.log("Addition:", result);
Output
Addition: 30
Explanation:
The require("./math") statement loads the function
exported from math.js. We store that function in
the variable add, call it with the values
10 and 20, and display the returned
result using console.log().
5. Creating a Module with Multiple Functions
A custom module can export multiple functions. We can group related operations in one file and export them together as an object.
Step 1: Create calculator.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
module.exports = {
add,
subtract,
multiply,
divide
};
Explanation: We define four functions for addition, subtraction, multiplication, and division. The exported object contains all four functions. The division function also checks whether the second number is zero before performing the calculation.
Step 2: Use calculator.js in app.js
const calculator = require("./calculator");
console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Multiplication:", calculator.multiply(20, 10));
console.log("Division:", calculator.divide(20, 10));
console.log("Division by zero:", calculator.divide(20, 0));
Output
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Division by zero: Cannot divide by zero
Explanation:
The variable calculator holds the object returned
by require("./calculator"). We access each exported
function using dot notation, such as
calculator.add() and calculator.multiply().
6. Import Specific Functions Using Destructuring
If we need only selected functions from an exported object, JavaScript object destructuring allows us to extract those functions directly.
Example
const { add, multiply } = require("./calculator");
console.log(add(5, 3));
console.log(multiply(5, 3));
Output
8
15
Here, add and multiply are extracted
from the object exported by calculator.js. We can
call them directly without writing
calculator.add() or calculator.multiply().
7. Creating a Student Custom Module
Custom modules are useful in real applications too. Let us create a student module that returns student information.
Step 1: Create student.js
function getStudentDetails(name, course, marks) {
return {
name: name,
course: course,
marks: marks
};
}
module.exports = getStudentDetails;
The getStudentDetails() function accepts a student's
name, course, and marks. It returns an object containing these
three properties.
Step 2: Create app.js
const getStudentDetails = require("./student");
const student = getStudentDetails(
"Samadhan",
"Node.js",
85
);
console.log("Student Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);
Output
Student Name: Samadhan
Course: Node.js
Marks: 85
Explanation: The main file imports the student function, passes the student's information as arguments, and receives the returned object. It then accesses the object's properties to display the details.
8. Student Module Program Flow
This diagram shows how the student module and the main application work together.
student.js
Defines and exports getStudentDetails().
app.js
Imports the function using require("./student").
Pass Student Information
Name, course, and marks are passed to the function.
Returned Student Object
The application reads and displays the student details.
9. Creating a Custom Module Using ES Modules
Node.js also supports ES Modules. In this module system,
we use export to share functionality and
import to use it in another file.
For this example, use the .mjs extension for
both files so Node.js treats them as ES Modules.
Step 1: Create message.mjs
export function getWelcomeMessage(name) {
return "Welcome to Node.js, " + name + "!";
}
Step 2: Create app.mjs
import { getWelcomeMessage } from "./message.mjs";
console.log(getWelcomeMessage("Student"));
Output
Welcome to Node.js, Student!
In this example, the export keyword makes the
function available to other ES Modules. The import
statement loads the named export into app.mjs.
require() and module.exports,
whereas the ES Module example uses import and
export.
10. How to Run a Custom Module Program
Follow these steps to execute the CommonJS calculator program.
-
Create a folder named
CustomModuleExample. -
Save the calculator functions in
calculator.js. -
Save the main program in
app.js. - Open a terminal in the project folder.
- Execute the main file using the Node.js command.
Terminal Command
node app.js
Node.js executes app.js. When it reaches
require("./calculator"), it loads the local
calculator module and makes its exported functionality
available to the main program.
./calculator refers to the
calculator.js file in the same folder for this
CommonJS example. Make sure both files are saved in the
expected location.
11. Common Mistakes When Creating Custom Modules
| Mistake | Correct Approach |
|---|---|
| Forgetting to export a function. | Use module.exports or an appropriate ES Module export. |
| Using an incorrect file path. | Check the relative path and filename. |
| Calling a function that was not exported. | Verify the exported values and function names. |
Using import in a CommonJS example without the correct setup. |
Use the module syntax supported by the file's configuration. |
| Keeping all logic in one large file. | Separate reusable functionality into focused modules. |
| Assuming an imported function automatically runs. | Call the function explicitly when its result is needed. |
12. Practice Tasks
Task 1: Create a Calculator Module
Create a file named calculator.js containing
addition, subtraction, multiplication, and division functions.
Export the functions and use them from app.js.
Challenge: Add a condition to handle division by zero.
Task 2: Create a Student Module
Create a file named student.js that exports
a function accepting a student's name, course, and marks.
Import the function into app.js and display
all three values.
Task 3: Create a Welcome Module
Create a module that exports a function named
getWelcomeMessage(). The function should accept
a name and return a welcome message. Import and call it
from another file.
Important Points
- A custom module is a file created by the developer to organize reusable functionality.
-
CommonJS uses
module.exportsto export values andrequire()to import them. - A module can export one function or an object containing multiple functions.
-
ES Modules use
exportandimport. -
Relative paths such as
./calculatorrefer to local files. - Separating code into modules improves readability, reusability, and maintainability.
Summary
Custom modules in Node.js allow developers to organize application logic into separate, reusable JavaScript files. CommonJS uses module.exports to expose functionality and require() to load it into another file, while ES Modules use export and import. We can create modules for calculations, student information, and other application features, then reuse their functions wherever required. Creating custom modules improves code organization, readability, maintainability, and code reusability in Node.js applications.