Introduction
The require() function is an important part of the CommonJS module system in Node.js. It allows you to load built-in Node.js modules, your own local modules, and installed packages into your application. In this chapter, you will practice require() with simple examples, including importing functions, objects, multiple modules, built-in modules, and external packages. These examples gradually move from beginner level to practical Node.js usage. Node.js require() practice questions with solutions help to understand the concepts.
Question 1: How do you import a local module using require()?
Problem
Create a simple module and import it into another Node.js file using require().
Solution
Create a file named message.js:
const message = "Hello from my module!";
module.exports = message;
Now create app.js:
const message = require("./message");
console.log(message);
Run:
node app.js
Output
Hello from my module!
Step-by-Step Explanation
- Create
message.js. - Store a message in a variable.
- Export the message using
module.exports. - Create
app.js. - Use
require("./message")to import the module. - Store the imported value in
message. - Display it using
console.log().
The ./ tells Node.js that message.js is a local file in the current directory.
Question 2: How do you use require() to import a function?
Problem
Create a function in one file and use require() to import and execute it from another file.
Solution
Create greeting.js:
function greet(name) {
return "Hello, " + name;
}
module.exports = greet;
Create app.js:
const greet = require("./greeting");
console.log(greet("Riya"));
Output
Hello, Riya
Step-by-Step Explanation
- Create a
greet()function. - Export the function with
module.exports. - Use
require("./greeting")inapp.js. - The returned value from
require()is the exported function. - Call
greet("Riya"). - The function returns the greeting.
This is one of the most common uses of require() in Node.js.
Question 3: How do you use require() to import an object?
Problem
Create a user object in one module and access its properties from another file.
Solution
Create user.js:
const user = {
name: "Aman",
age: 20,
city: "Delhi"
};
module.exports = user;
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 a
userobject. - Add
name,age, andcity. - Export the object.
- Import it using
require(). - Access the properties using dot notation.
- Display each value.
require() does not only import functions. It can also import objects, strings, numbers, and other exported values.
Question 4: How do you import multiple functions using require()?
Problem
Create a calculator module with three functions and use all of them in another file.
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 calculator functions.
- Put them inside an object.
- Export the object.
- Import the object using
require(). - Access each function through
calculator. - Call each function with two numbers.
This pattern is useful when one module contains several related functions.
Question 5: How do you use destructuring with require()?
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, 10));
console.log(multiply(5, 10));
Output
15
50
Step-by-Step Explanation
- The calculator module exports three functions.
require("./calculator")imports the exported object.{ add, multiply }extracts only the required functions.- The
subtractfunction is not stored in a local variable. add(5, 10)returns15.multiply(5, 10)returns50.
This is a convenient way to work with modules that export many values.
Question 6: How do you use require() with a built-in Node.js module?
Problem
Use Node.js’s built-in path module to find the file extension of a filename.
Solution
Create app.js:
const path = require("path");
const filename = "student.js";
console.log(path.extname(filename));
Run:
node app.js
Output
.js
Step-by-Step Explanation
pathis a built-in Node.js module.- Use
require("path")to load it. - Create a filename.
- Use
path.extname()to find its extension. - The result is
.js.
Notice that we do not use ./ with path because it is a Node.js built-in module.
Question 7: How do you use require() with the built-in os module?
Problem
Use the Node.js os module to display the operating system platform.
Solution
Create app.js:
const os = require("os");
console.log(os.platform());
Output
The exact output depends on your operating system.
For example, on Windows:
win32
On Linux:
linux
Step-by-Step Explanation
osis a built-in Node.js module.- Import it using
require("os"). os.platform()returns information about the operating system.- The result is displayed in the terminal.
Built-in modules are included with Node.js, so you don’t need to install them separately.
Question 8: How do you use require() with multiple built-in modules?
Problem
Use the path and os modules together.
Solution
Create app.js:
const path = require("path");
const os = require("os");
const filename = path.join("students", "data.txt");
console.log("File Path:", filename);
console.log("Platform:", os.platform());
Output
On Windows, the path separator may appear as \:
File Path: students\data.txt
Platform: win32
On Linux or macOS, the path separator may appear as /:
File Path: students/data.txt
Platform: linux
Step-by-Step Explanation
- Import the
pathmodule. - Import the
osmodule. - Use
path.join()to create a platform-aware path. - Use
os.platform()to identify the operating system. - Display both results.
This shows that a Node.js application can require multiple modules in the same file.
Question 9: How do you use require() with an installed package?
Problem
Install and use an external npm package with require().
Solution
For this example, install the lodash package:
npm install lodash
Create app.js:
const _ = require("lodash");
const numbers = [10, 20, 30, 40];
const total = _.sum(numbers);
console.log(total);
Output
100
Step-by-Step Explanation
- Run
npm install lodash. - Node.js downloads the package into your project.
require("lodash")loads the installed package.- The package is stored in
_. _.sum()calculates the total.- The result is
100.
Unlike local modules, you do not use ./ when requiring an installed package.
Note: Modern Node.js also supports ES Modules, but this example specifically demonstrates the CommonJS
require()approach.
Question 10: How do you use require() with multiple custom modules in a small application?
Problem
Create a simple student 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 usingrequire().- The student’s marks are passed to
checkResult(). - The function checks whether the marks are
40or higher. - The final result is displayed.
This example shows how require() can connect different parts of a real Node.js application.
Key Takeaways
require()is commonly used with the CommonJS module system in Node.js.require()loads and returns the value exported by a module.- Local modules are commonly loaded using paths such as
./message. - Built-in modules can be loaded using names such as
pathandos. - Installed npm packages can also be loaded using
require(). module.exportsdetermines what another file receives fromrequire().- You can use
require()to import functions, objects, variables, and other exported values. - Destructuring can be used to import specific properties from an exported object.
- Multiple modules can be loaded in the same Node.js file.
- The
./prefix generally indicates a local module rather than a built-in module or installed package. require()is mainly associated with CommonJS modules.
FAQs
1. What is require() in Node.js?
require() is a CommonJS function used to load modules into a Node.js file. It returns whatever value the module exports.
Example:
const calculator = require("./calculator");
2. What does require("./file") mean?
The ./ tells Node.js to look for the module relative to the current file.
For example:
const message = require("./message");
means that Node.js should load the local message module.
3. Can require() import built-in Node.js modules?
Yes. You can use require() to load built-in modules such as:
const path = require("path");
const os = require("os");
const fs = require("fs");
These modules are provided by Node.js and do not normally need to be installed separately.
4. Can require() import npm packages?
Yes. After installing an npm package, you can generally load a CommonJS-compatible package using require().
For example:
const lodash = require("lodash");
5. What is the difference between require() and import?
require() is associated with the CommonJS module system:
const math = require("./math");
ES Modules use import:
import math from "./math.js";
Both systems are supported by Node.js, but they use different module syntax and configuration rules.
6. Why do we use ./ with local modules?
The ./ indicates that the module is located relative to the current file.
For example:
require("./calculator");
tells Node.js to look for a local calculator module.
7. What happens if a module does not export anything?
If a CommonJS module does not explicitly assign a value to module.exports, its default exported value is an empty object.
For example:
const data = require("./empty");
If empty.js does not export anything, data will normally be:
{}
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
