Introduction
The require() function is one of the most important concepts in Node.js CommonJS modules. It allows you to load local files, built-in Node.js modules, and installed packages into your application. In this chapter, you will get more hands-on practice with require() through simple, step-by-step examples. These questions focus on practical usage so beginners can understand how different Node.js files and modules work together. Node.js require() practice questions with solutions help to understand the concepts.
Question 1: How do you import a string using require()?
Problem
Create a separate file containing a welcome message and import it into app.js.
Solution
Create message.js:
const message = "Welcome to Node.js!";
module.exports = message;
Create app.js:
const message = require("./message");
console.log(message);
Run:
node app.js
Output
Welcome to Node.js!
Step-by-Step Explanation
- Create
message.js. - Store the message in a variable.
- Export it using
module.exports. - Create
app.js. - Use
require("./message")to import the module. - Store the returned value in
message. - Print the message.
Question 2: How do you import and use a function with require()?
Problem
Create a function that calculates the area of a rectangle and use it from another file.
Solution
Create rectangle.js:
function area(length, width) {
return length * width;
}
module.exports = area;
Create app.js:
const area = require("./rectangle");
const result = area(10, 5);
console.log("Area:", result);
Run:
node app.js
Output
Area: 50
Step-by-Step Explanation
- Create the
area()function. - The function accepts
lengthandwidth. - Multiply both values.
- Export the function.
- Import it using
require(). - Call
area(10, 5). - The result is
50.
Question 3: How do you import an object using require()?
Problem
Create a student object in one file and display its information in another file.
Solution
Create student.js:
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
module.exports = student;
Create app.js:
const student = require("./student");
console.log("Name:", student.name);
console.log("Age:", student.age);
console.log("Course:", student.course);
Output
Name: Riya
Age: 18
Course: Node.js
Step-by-Step Explanation
- Create a student object.
- Add three properties.
- Export the object.
- Import it with
require(). - Use dot notation to access each property.
- Display the information.
Question 4: How do you require multiple functions from one module?
Problem
Create a calculator module with addition, subtraction, and division functions.
Solution
Create calculator.js:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function divide(a, b) {
return a / b;
}
module.exports = {
add,
subtract,
divide
};
Create app.js:
const calculator = require("./calculator");
console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Division:", calculator.divide(20, 10));
Output
Addition: 30
Subtraction: 10
Division: 2
Step-by-Step Explanation
- Create three calculator functions.
- Put them inside an object.
- Export the object.
- Import the object using
require(). - Access each function using dot notation.
- Call the functions with different values.
Question 5: How do you use destructuring with require()?
Problem
Import only the add() and divide() functions from the calculator module.
Solution
Use the same calculator.js:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function divide(a, b) {
return a / b;
}
module.exports = {
add,
subtract,
divide
};
Create app.js:
const { add, divide } = require("./calculator");
console.log(add(10, 20));
console.log(divide(20, 5));
Output
30
4
Step-by-Step Explanation
- The calculator module exports three functions.
require()loads the exported object.{ add, divide }extracts only the required functions.subtractis not imported into the local scope.- Call
add()anddivide()directly.
This is useful when a module exports many functions but you only need a few.
Question 6: How do you use require() with the Node.js path module?
Problem
Use the built-in path module to create a file path.
Solution
Create app.js:
const path = require("path");
const filePath = path.join("documents", "notes", "data.txt");
console.log(filePath);
Run:
node app.js
Output
On Windows, you may see:
documents\notes\data.txt
On Linux or macOS:
documents/notes/data.txt
Step-by-Step Explanation
pathis a built-in Node.js module.- Import it using
require("path"). - Use
path.join(). - Pass the folder and file names.
- Node.js creates the appropriate path for the operating system.
- Display the result.
You do not need to install the path module separately.
Question 7: How do you use require() with the Node.js fs module?
Problem
Create a text file using Node.js’s built-in File System module.
Solution
Create app.js:
const fs = require("fs");
fs.writeFileSync("message.txt", "Hello from Node.js!");
console.log("File created successfully.");
Run:
node app.js
Output
File created successfully.
A new file named message.txt will be created in the current folder.
Its content will be:
Hello from Node.js!
Step-by-Step Explanation
- Import the
fsmodule usingrequire(). fsstands for File System.- Use
writeFileSync(). - Provide the filename.
- Provide the content.
- Node.js creates the file.
- The success message appears in the terminal.
Question 8: How do you use require() with the Node.js os module?
Problem
Display information about your computer using the built-in os module.
Solution
Create app.js:
const os = require("os");
console.log("Platform:", os.platform());
console.log("Architecture:", os.arch());
console.log("CPU Cores:", os.cpus().length);
Output
The exact values depend on your computer.
For example:
Platform: win32
Architecture: x64
CPU Cores: 8
Step-by-Step Explanation
- Import the
osmodule. os.platform()returns the operating system platform.os.arch()returns the CPU architecture.os.cpus()returns CPU information..lengthcounts the available CPU entries.- Display the information.
This is a practical example of using require() with a built-in Node.js module.
Question 9: How do you require multiple local modules in one application?
Problem
Create separate modules for a greeting and a calculator, then use both modules in app.js.
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;
Create app.js:
const greet = require("./greeting");
const square = require("./calculator");
console.log(greet("Aman"));
console.log("Square:", square(7));
Output
Hello, Aman
Square: 49
Step-by-Step Explanation
- Create the greeting module.
- Export the
greet()function. - Create the calculator module.
- Export the
square()function. - Import both modules using
require(). - Call the greeting function.
- Call the square function.
- Display both results.
This is how different files can work together in a Node.js project.
Question 10: How do you build a small application using require()?
Problem
Create a simple student result application using three separate files.
Solution
Create student.js:
const student = {
name: "Aarav",
marks: 78
};
module.exports = student;
Create result.js:
function checkResult(marks) {
if (marks >= 40) {
return "Pass";
}
return "Fail";
}
module.exports = checkResult;
Create message.js:
function getMessage(name, result) {
return `${name} has ${result}ed the examination.`;
}
module.exports = getMessage;
Create app.js:
const student = require("./student");
const checkResult = require("./result");
const getMessage = require("./message");
const result = checkResult(student.marks);
console.log("Student:", student.name);
console.log("Marks:", student.marks);
console.log("Result:", result);
console.log(getMessage(student.name, result));
Run:
node app.js
Output
Student: Aarav
Marks: 78
Result: Pass
Aarav has Passed the examination.
Step-by-Step Explanation
student.jsstores student information.result.jschecks whether the student passed.message.jscreates a final message.- All three modules export their required values or functions.
app.jsimports all three usingrequire().- The student’s marks are passed to
checkResult(). - The result is passed to
getMessage(). - The application displays the final information.
This example demonstrates how require() connects several CommonJS modules to create a small application.
Key Takeaways
require()is mainly used with Node.js CommonJS modules.require()loads a module and returns its exported value.- Use
./when importing a local module. - Built-in modules such as
fs,path, andoscan be loaded withrequire(). - Installed npm packages can also be loaded with
require(). module.exportscontrols what another file receives fromrequire().- You can require functions, objects, strings, numbers, and other values.
- Destructuring can be used with
require()when a module exports an object. - One application can require several different modules.
- Breaking an application into modules makes the code easier to organize and maintain.
FAQs
1. What is require() in Node.js?
require() is a CommonJS function used to load modules into a Node.js application.
Example:
const calculator = require("./calculator");
2. How do I require a local JavaScript file?
Use a relative path beginning with ./.
const message = require("./message");
If the file is inside another folder, you can use a path such as:
const user = require("./models/user");
3. Can I use require() for built-in Node.js modules?
Yes. Node.js provides many built-in modules that can be loaded using require().
const fs = require("fs");
const path = require("path");
const os = require("os");
4. Can require() import functions?
Yes. A module can export a function using module.exports, and another file can import it using require().
const greet = require("./greeting");
console.log(greet("Riya"));
5. What is the difference between require() and module.exports?
require() is used to import/load a module, while module.exports is used to export something from a CommonJS module.
const add = require("./calculator");
module.exports = add;
6. Can I use multiple require() statements in one file?
Yes. You can load multiple modules in the same file.
const fs = require("fs");
const path = require("path");
const os = require("os");
7. Does require() work with ES Modules?
CommonJS and ES Modules use different module systems. ES Modules normally use import and export, while CommonJS uses require() and module.exports. Node.js supports both, but mixing them requires understanding Node.js module interoperability rules.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
