Introduction
Node.js modules help you organize your application into separate, reusable files. Instead of putting all your code into one large file, you can divide it into smaller modules and use them whenever needed. In this chapter, you will practice creating your own modules, exporting values and functions, importing modules with require(), and using multiple modules together. These examples start with simple concepts and gradually build your Node.js module skills. Node.js Modules practice questions with solutions help to understand the concepts.
Question 1: How do you create a simple Node.js module?
Problem
Create a module that stores a simple message and export it so another file can use it.
Solution
Create a file named message.js:
const message = "Welcome to Node.js modules!";
module.exports = message;
Now create another file named app.js:
const message = require("./message");
console.log(message);
Run:
node app.js
Output
Welcome to Node.js modules!
Step-by-Step Explanation
- Create
message.js. - Store a message inside the
messagevariable. module.exportsmakes the message available outside the file.- Create
app.js. require("./message")imports the module.- The imported message is stored in the
messagevariable. console.log()displays the message.
The ./ tells Node.js to look for the module in the current folder.
Question 2: How do you export a function from a Node.js module?
Problem
Create a module containing a function that displays a welcome message.
Solution
Create greeting.js:
function greet() {
return "Hello from the greeting module!";
}
module.exports = greet;
Create app.js:
const greet = require("./greeting");
console.log(greet());
Run:
node app.js
Output
Hello from the greeting module!
Step-by-Step Explanation
- Create a function called
greet(). - The function returns a message.
module.exports = greetexports the function.require("./greeting")imports the function.greet()calls the imported function.- The returned message is displayed.
This is useful when you want to keep reusable functions in separate files.
Question 3: How do you create a module for adding two numbers?
Problem
Create a module that contains an addition function and use it in another file.
Solution
Create calculator.js:
function add(a, b) {
return a + b;
}
module.exports = add;
Create app.js:
const add = require("./calculator");
const result = add(10, 20);
console.log(result);
Run:
node app.js
Output
30
Step-by-Step Explanation
- Create the
add()function insidecalculator.js. - The function accepts two parameters.
- It returns their sum.
- Export the function using
module.exports. - Import it into
app.js. - Call
add(10, 20). - The result is
30.
Separating calculator functions into a module makes the code easier to reuse.
Question 4: How do you export multiple functions from a Node.js module?
Problem
Create a calculator module containing functions for addition and subtraction.
Solution
Create calculator.js:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
Create app.js:
const calculator = require("./calculator");
console.log(calculator.add(20, 10));
console.log(calculator.subtract(20, 10));
Output
30
10
Step-by-Step Explanation
- Create two functions:
add()andsubtract(). - Put both functions inside an object.
- Export the object using
module.exports. - Import the object into
app.js. - Use
calculator.add()to call the addition function. - Use
calculator.subtract()to call the subtraction function.
A module can export multiple values or functions.
Question 5: How do you export multiple values from a Node.js module?
Problem
Create a module containing a person’s name, age, and city.
Solution
Create user.js:
const name = "Aman";
const age = 20;
const city = "Delhi";
module.exports = {
name,
age,
city
};
Create app.js:
const user = require("./user");
console.log(user.name);
console.log(user.age);
console.log(user.city);
Output
Aman
20
Delhi
Step-by-Step Explanation
- Create three variables.
- Put the variables inside an object.
- Export the object.
- Import the object in
app.js. - Access each value using dot notation.
- Display the values using
console.log().
This approach is useful for sharing related information between files.
Question 6: How do you import specific functions from a module?
Problem
Create a calculator module with three functions and import only the functions you need.
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, 10));
console.log(multiply(5, 10));
Output
15
50
Step-by-Step Explanation
- The calculator module exports three functions.
require("./calculator")imports the module.{ add, multiply }selects the required functions.- The
subtractfunction is not imported. add(5, 10)returns15.multiply(5, 10)returns50.
This technique is called destructuring and is useful when a module exports several values.
Question 7: How do you create a reusable student module?
Problem
Create a module that contains a function for displaying a student’s information.
Solution
Create student.js:
function showStudent(name, age, course) {
console.log("Name:", name);
console.log("Age:", age);
console.log("Course:", course);
}
module.exports = showStudent;
Create app.js:
const showStudent = require("./student");
showStudent("Riya", 18, "Node.js");
Output
Name: Riya
Age: 18
Course: Node.js
Step-by-Step Explanation
- Create a function called
showStudent(). - The function accepts three values.
- It displays the student’s information.
- Export the function.
- Import it into
app.js. - Pass student information to the function.
- Node.js executes the function and displays the information.
Reusable modules are especially useful in larger applications.
Question 8: How do you create a module for checking even numbers?
Problem
Create a module that checks whether a number is even.
Solution
Create number.js:
function isEven(number) {
return number % 2 === 0;
}
module.exports = isEven;
Create app.js:
const isEven = require("./number");
console.log(isEven(10));
console.log(isEven(7));
Output
true
false
Step-by-Step Explanation
- Create the
isEven()function. %calculates the remainder.- An even number has a remainder of
0when divided by2. - The function returns
truefor an even number. - Export the function.
- Import it into
app.js. - Test it with
10and7.
This example shows how modules can contain reusable application logic.
Question 9: How do you use more than one custom module?
Problem
Create two separate modules and use both of them in the same Node.js application.
Solution
Create greeting.js:
function greet(name) {
return "Hello, " + name;
}
module.exports = greet;
Create calculator.js:
function square(number) {
return number * number;
}
module.exports = square;
Now create app.js:
const greet = require("./greeting");
const square = require("./calculator");
console.log(greet("Rahul"));
console.log(square(5));
Output
Hello, Rahul
25
Step-by-Step Explanation
greeting.jscontains the greeting function.calculator.jscontains the square function.- Both functions are exported separately.
app.jsimports both modules.greet("Rahul")creates the greeting.square(5)calculates25.- Both results are displayed.
Using multiple modules keeps different parts of an application separated and organized.
Question 10: How do you create a small Node.js application using modules?
Problem
Create a simple student result application using separate modules for student information and result calculation.
Solution
Create student.js:
const student = {
name: "Aarav",
marks: 85
};
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: 85
Result: Pass
Step-by-Step Explanation
student.jsstores student information.- The student object is exported.
result.jscontains the result-checking function.- The function is exported.
app.jsimports both modules.- 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 demonstrates why modules are useful in real applications: each file has a clear responsibility.
Key Takeaways
- A Node.js module is a reusable piece of code.
- Modules help divide a large application into smaller files.
module.exportsis used to export values or functions.require()can be used to import CommonJS modules.- A module can export a single value or multiple values.
- Functions can be exported and reused in other files.
- Objects can contain multiple exported functions or values.
- Custom modules are usually imported using a relative path such as
./calculator. - Multiple modules can be used in the same Node.js application.
- Modules make Node.js applications easier to organize, maintain, and reuse.
FAQs
1. What is a module in Node.js?
A module is a separate, reusable piece of code. In Node.js, modules allow you to divide an application into multiple files instead of putting everything into one file.
2. Why are modules used in Node.js?
Modules are used to organize code, improve reusability, reduce complexity, and make applications easier to maintain.
3. What is module.exports in Node.js?
module.exports is used in CommonJS modules to make values, objects, or functions available to other files.
4. What does require() do in Node.js?
require() is used to import a CommonJS module so that its exported values or functions can be used in another file.
5. Can one Node.js module export multiple functions?
Yes. You can export multiple functions by placing them inside an object.
module.exports = {
add,
subtract,
multiply
};
6. Can I use multiple modules in one Node.js application?
Yes. A Node.js application can import and use many different modules. For example, you can have separate modules for users, products, authentication, calculations, and database operations.
7. What is the difference between a module and a JavaScript file?
A JavaScript file becomes a module when it is used as a reusable unit of code, typically by exporting values or functions and importing them into another file. In Node.js, a file can serve as a module.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
