CommonJS Modules in Node.js
Learn how to export and import functions, variables and objects using the CommonJS module system in Node.js.
1. What Is CommonJS?
CommonJS is a module system traditionally used by Node.js to organize JavaScript code into separate files. It allows one file to expose functionality and another file to load and use that functionality.
For example, suppose an application needs addition, subtraction, multiplication and division operations. We can write these functions in a separate calculator module and reuse them in other files.
CommonJS primarily uses two mechanisms:
-
module.exports: Exposes values or functionality from a module. -
require(): Loads the exported value from another module.
2. Why Do We Use CommonJS Modules?
CommonJS helps developers organize code so that each file can handle a particular responsibility.
- Reusability: Use the same function in multiple files.
- Organization: Keep related logic together.
- Maintainability: Update a module without duplicating its code.
- Readability: Make large applications easier to understand.
- Separation of Responsibilities: Separate calculation, validation and other tasks.
3. How CommonJS Works
A CommonJS module exports a value, and another file loads that
value using require().
math.js
Define the reusable function.
function add(a, b) { ... }
module.exports
Expose the function to other files.
module.exports = add;
app.js
Load the exported function.
const add = require("./math");
Use the Function
add(10, 20)
Result: 30
4. Understanding module.exports
The module.exports object determines what a CommonJS
module makes available to other files.
You can export a function, an object, an array or another value.
The importing file receives that exported value from
require().
Example: Export a Single Function
Create a file named greeting.js.
function greet() {
return "Welcome to Node.js!";
}
module.exports = greet;
Now create app.js to use the function.
const greet = require("./greeting");
console.log(greet());
Expected Output
Welcome to Node.js!
Explanation
- The
greet()function is defined ingreeting.js. module.exports = greetexposes the function.require("./greeting")loads the exported function.greet()calls the function and returns the message.console.log()displays the returned message.
5. Export Multiple Functions
A module can expose multiple functions through an object. This is useful when several operations belong to the same feature.
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;
}
module.exports = {
add,
subtract,
multiply
};
Step 2: Use the Functions 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));
Expected Output
Addition: 30 Subtraction: 10 Multiplication: 200
The imported calculator variable refers to the object
exported by calculator.js. Its methods are accessed
using dot notation.
6. Destructuring Imported Functions
Instead of accessing every function through the module object, we can use object destructuring to extract the required functions.
const { add, subtract } = require("./calculator");
console.log(add(15, 5));
console.log(subtract(15, 5));
Expected Output
20 10
Here, add and subtract are extracted
from the object returned by require("./calculator").
7. Understanding exports
Node.js also provides an exports shortcut that initially
refers to the same object as module.exports.
You can attach properties to it to expose multiple values.
Example
exports.add = function(a, b) {
return a + b;
};
exports.multiply = function(a, b) {
return a * b;
};
Import the exported functions in app.js.
const calculator = require("./calculator");
console.log(calculator.add(5, 3));
console.log(calculator.multiply(5, 3));
Expected Output
8 15
exports
directly with a new value. For example,
exports = function() {} does not replace
module.exports. Use module.exports = ...
when exporting a single function or a completely new value.
8. module.exports vs exports
| Feature | module.exports | exports |
|---|---|---|
| Purpose | Defines the value exported by the module. | Shortcut for adding properties to the initial export object. |
| Export a single function | module.exports = greet; |
Not by reassigning exports directly. |
| Export multiple properties | module.exports = { add, subtract }; |
exports.add = add; |
| Can replace the exported value? | Yes. | Reassigning the local exports variable does not replace the exported value. |
9. How Multiple Exports Work
When multiple functions are exported as object properties, the importing file can access each function using its property name.
Create Functions
add(), subtract(), multiply()
module.exports
{ add, subtract, multiply }
app.js
const calculator = require("./calculator");
Call the Methods
calculator.add(20, 10)
Result: 30
10. Practical Example: Student Module
Consider a student management application. We can place student-related functionality in a separate module and use it in the main application.
Step 1: Create student.js
function getStudentDetails(name, course) {
return {
name: name,
course: course
};
}
module.exports = getStudentDetails;
Step 2: Create app.js
const getStudentDetails = require("./student");
const student = getStudentDetails("Samadhan", "Node.js");
console.log("Student:", student.name);
console.log("Course:", student.course);
Expected Output
Student: Samadhan Course: Node.js
Explanation
- The student module defines a function that creates a student object.
- The function is exported using
module.exports. - The main file loads the function using
require(). - The function receives a student name and course name.
- The returned object is used to display the student's details.
11. How to Run a CommonJS Program
Save the example files in the same folder. For example:
CommonJSExample/
app.js
calculator.js
student.js
Open a terminal in the project folder and execute:
node app.js
Node.js executes app.js, loads the required local
modules and displays the output.
require() statements match your actual files.
12. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Forgetting to export a function. | Expose it using module.exports or a property on exports. |
| Using an incorrect module path. | Verify the relative path and filename. |
| Calling a method that was not exported. | Check the names of exported properties. |
Writing exports = value to replace the module export. |
Assign the value to module.exports. |
| Mixing CommonJS with ES Module syntax without checking configuration. | Confirm which module system the file uses. |
13. Practice Tasks
Task 1: Create a Calculator Module
Create a file named calculator.js. Add functions
for addition, subtraction and multiplication. Export all three
functions and use them from app.js.
Addition: 30
Subtraction: 10
Multiplication: 200
Task 2: Create a Student Module
Create a function that accepts a student name and course, returns an object, and exports the function. Import it in another file and display the details.
Expected Output:Student: Pradnya
Course: JavaScript
Task 3: Export Multiple Values
Create a module that exports a constant named
instituteName and a function named
getWelcomeMessage(). Import both in another file
and display their values.
Summary
CommonJS is a module system traditionally used in Node.js to organize JavaScript code into reusable files. The module.exports property exposes functions, objects, and other values, while require() loads those exported values into another file. The exports shortcut can add properties to the module's export object, but assigning a new value directly to exports does not replace module.exports. CommonJS modules improve code reusability, readability, maintainability, and separation of responsibilities in Node.js applications.