Introduction
CommonJS is the traditional module system widely used in Node.js applications. It allows you to split code into separate files and share functions, variables, objects, and classes between them. In this chapter, you will practice require(), module.exports, exports, exporting multiple values, importing specific functions, and using multiple CommonJS modules together. The examples start from basic concepts and gradually move toward practical Node.js usage. Node.js CommonJS Modules practice questions with solutions help to understand the concepts.
Question 1: How do you export a simple value using CommonJS?
Problem
Create a CommonJS module that exports a simple message and use that message in another file.
Solution
Create a file named message.js:
const message = "Hello from CommonJS!";
module.exports = message;
Create another file named app.js:
const message = require("./message");
console.log(message);
Run:
node app.js
Output
Hello from CommonJS!
Step-by-Step Explanation
- Create
message.js. - Store a message in the
messagevariable. module.exportsmakes the message available to other files.- Create
app.js. require("./message")imports the exported value.console.log()displays the message.
This is the basic pattern of a CommonJS module.
Question 2: How do you export a function using CommonJS?
Problem
Create a CommonJS module that exports a greeting function.
Solution
Create greeting.js:
function greet(name) {
return "Hello, " + name + "!";
}
module.exports = greet;
Create app.js:
const greet = require("./greeting");
console.log(greet("Riya"));
Run:
node app.js
Output
Hello, Riya!
Step-by-Step Explanation
- Create a
greet()function. - The function accepts a
nameparameter. - The function returns a greeting.
module.exports = greetexports the function.require("./greeting")imports the function.greet("Riya")calls the imported function.
Functions are commonly exported because they can be reused throughout an application.
Question 3: How do you export multiple functions using CommonJS?
Problem
Create a calculator module containing addition, subtraction, and multiplication functions.
Solution
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
};
Create app.js:
const calculator = require("./calculator");
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
console.log(calculator.multiply(10, 5));
Output
15
5
50
Step-by-Step Explanation
- Create three separate functions.
- Put the functions inside an object.
- Assign the object to
module.exports. - Import the object using
require(). - Use dot notation to access each function.
- Call the functions with different values.
This is a common way to export multiple functions from a CommonJS module.
Question 4: How do you import specific functions from a CommonJS module?
Problem
Import only the add() and multiply() functions from a calculator module.
Solution
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
};
Create app.js:
const { add, multiply } = require("./calculator");
console.log(add(5, 5));
console.log(multiply(5, 5));
Output
10
25
Step-by-Step Explanation
- The calculator module exports three functions.
require("./calculator")loads the module.{ add, multiply }extracts only the required functions.subtractis not imported.add(5, 5)returns10.multiply(5, 5)returns25.
This uses JavaScript destructuring with CommonJS modules.
Question 5: How do you export multiple values using CommonJS?
Problem
Create a module containing a student’s name, age, and course.
Solution
Create student.js:
const name = "Aman";
const age = 19;
const course = "Node.js";
module.exports = {
name,
age,
course
};
Create app.js:
const student = require("./student");
console.log("Name:", student.name);
console.log("Age:", student.age);
console.log("Course:", student.course);
Output
Name: Aman
Age: 19
Course: Node.js
Step-by-Step Explanation
- Create three variables.
- Put the variables inside an object.
- Export the object using
module.exports. - Import the object using
require(). - Access the values using dot notation.
- Display them in the terminal.
CommonJS modules can export more than just functions.
Question 6: How do you use the exports object in CommonJS?
Problem
Create a CommonJS module using exports to export two functions.
Solution
Create math.js:
exports.add = function (a, b) {
return a + b;
};
exports.square = function (number) {
return number * number;
};
Create app.js:
const math = require("./math");
console.log(math.add(10, 20));
console.log(math.square(5));
Output
30
25
Step-by-Step Explanation
exports.addcreates an exportedaddproperty.exports.squarecreates an exportedsquareproperty.- Both functions become available outside the module.
require("./math")imports them.math.add()calls the addition function.math.square()calls the square function.
exports is commonly used when you want to add multiple properties to a module’s exported object.
Question 7: What is the difference between module.exports and exports?
Problem
Use both module.exports and exports correctly in CommonJS.
Solution
You can use exports like this:
exports.greet = function () {
return "Hello!";
};
exports.bye = function () {
return "Goodbye!";
};
This is equivalent to exporting an object with module.exports:
module.exports = {
greet: function () {
return "Hello!";
},
bye: function () {
return "Goodbye!";
}
};
Output
When imported:
const messages = require("./messages");
console.log(messages.greet());
console.log(messages.bye());
Output:
Hello!
Goodbye!
Step-by-Step Explanation
- Node.js provides
exportsas a convenient reference to the module’s exports object. - You can add properties using
exports.name. module.exportsis the actual value returned byrequire().- Both approaches can be used to export multiple properties.
- When exporting a single function or value directly, use
module.exports.
For example:
module.exports = greet;
is appropriate when the module itself should represent the greet function.
Question 8: How do you export an object using CommonJS?
Problem
Create a reusable user object and export it from a CommonJS module.
Solution
Create user.js:
const user = {
name: "Rahul",
age: 21,
city: "Delhi"
};
module.exports = user;
Create app.js:
const user = require("./user");
console.log("Name:", user.name);
console.log("Age:", user.age);
console.log("City:", user.city);
Output
Name: Rahul
Age: 21
City: Delhi
Step-by-Step Explanation
- Create a
userobject. - Add three properties to the object.
- Export the object using
module.exports. - Import the object into
app.js. - Access each property using dot notation.
- Display the information.
Objects are useful when several related values need to be shared between modules.
Question 9: How do you use multiple CommonJS modules together?
Problem
Create separate modules for greeting and calculating a square, then use both modules in one application.
Solution
Create greeting.js:
function greet(name) {
return "Welcome, " + name;
}
module.exports = greet;
Create math.js:
function square(number) {
return number * number;
}
module.exports = square;
Create app.js:
const greet = require("./greeting");
const square = require("./math");
console.log(greet("Aarav"));
console.log(square(6));
Output
Welcome, Aarav
36
Step-by-Step Explanation
greeting.jscontains the greeting function.math.jscontains the square function.- Both functions are exported separately.
app.jsimports both modules.greet()creates the welcome message.square()calculates the square.- Both results are displayed.
This is how larger Node.js applications can be divided into smaller, manageable modules.
Question 10: How do you build a small application using CommonJS modules?
Problem
Create a simple student result application using separate CommonJS modules.
Solution
Create student.js:
const student = {
name: "Aarav",
marks: 82
};
module.exports = student;
Create result.js:
function checkResult(marks) {
if (marks >= 40) {
return "Pass";
}
return "Fail";
}
module.exports = checkResult;
Create app.js:
const student = require("./student");
const checkResult = require("./result");
const result = checkResult(student.marks);
console.log("Student:", student.name);
console.log("Marks:", student.marks);
console.log("Result:", result);
Run:
node app.js
Output
Student: Aarav
Marks: 82
Result: Pass
Step-by-Step Explanation
student.jscontains student information.module.exportsexports the student object.result.jscontains thecheckResult()function.- The function is exported using
module.exports. app.jsimports both modules usingrequire().- The student’s marks are passed to
checkResult(). - The function checks whether the marks are at least
40. - The final result is displayed.
This example combines the most important CommonJS concepts from this chapter.
Key Takeaways
- CommonJS is a module system commonly used in Node.js.
require()is used to import CommonJS modules.module.exportsis used to export values from a module.- You can export functions, objects, strings, numbers, and other values.
- A module can export multiple functions or values.
exportscan be used to add properties to the module’s exported object.module.exportsrepresents the value returned byrequire().- Destructuring can be used to import specific exported properties.
- Multiple CommonJS modules can be used in the same application.
- CommonJS helps keep Node.js applications organized and reusable.
FAQs
1. What is CommonJS in Node.js?
CommonJS is a module system used in Node.js to organize JavaScript code into separate, reusable files. It commonly uses require() for importing and module.exports for exporting.
2. What is require() in CommonJS?
require() is used to load a CommonJS module and access the values or functions exported by that module.
Example:
const calculator = require("./calculator");
3. What is module.exports used for?
module.exports is used to make a value, function, object, or other data available to another file.
Example:
module.exports = add;
4. What is the difference between exports and module.exports?
exports is initially a reference to module.exports. You can add properties using exports.name. However, when replacing the entire exported value, you should use module.exports.
5. Can CommonJS export multiple functions?
Yes. Multiple functions can be exported as properties of an object.
module.exports = {
add,
subtract,
multiply
};
6. Can I use CommonJS modules in different files?
Yes. You can create separate CommonJS modules and import them into other files using require().
7. Is CommonJS still used in Node.js?
Yes. CommonJS remains widely used in Node.js projects and many existing packages and applications use it. Node.js also supports the modern ES module system, which you can learn separately.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
