Node.js require() Practice Questions with solutions

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

  1. Create message.js.
  2. Store a message in a variable.
  3. Export the message using module.exports.
  4. Create app.js.
  5. Use require("./message") to import the module.
  6. Store the imported value in message.
  7. 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

  1. Create a greet() function.
  2. Export the function with module.exports.
  3. Use require("./greeting") in app.js.
  4. The returned value from require() is the exported function.
  5. Call greet("Riya").
  6. 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

  1. Create a user object.
  2. Add name, age, and city.
  3. Export the object.
  4. Import it using require().
  5. Access the properties using dot notation.
  6. 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

  1. Create three calculator functions.
  2. Put them inside an object.
  3. Export the object.
  4. Import the object using require().
  5. Access each function through calculator.
  6. 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

  1. The calculator module exports three functions.
  2. require("./calculator") imports the exported object.
  3. { add, multiply } extracts only the required functions.
  4. The subtract function is not stored in a local variable.
  5. add(5, 10) returns 15.
  6. multiply(5, 10) returns 50.

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

  1. path is a built-in Node.js module.
  2. Use require("path") to load it.
  3. Create a filename.
  4. Use path.extname() to find its extension.
  5. 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

  1. os is a built-in Node.js module.
  2. Import it using require("os").
  3. os.platform() returns information about the operating system.
  4. 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

  1. Import the path module.
  2. Import the os module.
  3. Use path.join() to create a platform-aware path.
  4. Use os.platform() to identify the operating system.
  5. 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

  1. Run npm install lodash.
  2. Node.js downloads the package into your project.
  3. require("lodash") loads the installed package.
  4. The package is stored in _.
  5. _.sum() calculates the total.
  6. 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

  1. student.js stores student information.
  2. The student object is exported.
  3. result.js contains the result-checking function.
  4. The function is exported.
  5. app.js imports both modules using require().
  6. The student’s marks are passed to checkResult().
  7. The function checks whether the marks are 40 or higher.
  8. 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 path and os.
  • Installed npm packages can also be loaded using require().
  • module.exports determines what another file receives from require().
  • 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.

Scroll to Top