Node.js Built-in Modules Practice Questions with Solutions

Introduction

Node.js provides many built-in modules that help developers perform common tasks without installing extra packages. These modules can work with files, paths, operating system information, URLs, events, and more. In this chapter, you will practice important Node.js built-in modules such as fs, path, os, url, and events. Each example is simple, step by step, and designed to build practical Node.js skills from beginner to intermediate level. Node.js Built-in Modules practice questions with solutions help to understand the concepts.

Question 1: How do you check the operating system using the os module?

Problem

Use the Node.js built-in os module to display the operating system platform and CPU architecture.

Solution

Create app.js:

const os = require("os");

console.log("Operating System:", os.platform());
console.log("Architecture:", os.arch());

Run:

node app.js

Output

The output depends on your computer.

For example:

Operating System: win32
Architecture: x64

Step-by-Step Explanation

  1. Import the built-in os module using require().
  2. os.platform() returns information about the operating system.
  3. os.arch() returns the CPU architecture.
  4. console.log() displays the information.

You do not need to install the os module because it is already included with Node.js.


Question 2: How do you find the number of CPU cores using the os module?

Problem

Use the os module to find how many CPU entries are available on the computer.

Solution

const os = require("os");

const cpuCount = os.cpus().length;

console.log("CPU Cores:", cpuCount);

Output

The exact output depends on your computer.

CPU Cores: 8

Step-by-Step Explanation

  1. Import the os module.
  2. os.cpus() returns information about the available CPU cores.
  3. .length counts the returned CPU entries.
  4. Store the number in cpuCount.
  5. Display the result.

This can be useful when building applications that need information about the computer running Node.js.


Question 3: How do you create a file using the fs module?

Problem

Create a file named notes.txt and write some text into it.

Solution

const fs = require("fs");

fs.writeFileSync(
    "notes.txt",
    "Learning Node.js built-in modules."
);

console.log("File created successfully.");

Run:

node app.js

Output

File created successfully.

A new file called notes.txt will be created.

Its content will be:

Learning Node.js built-in modules.

Step-by-Step Explanation

  1. Import the fs module.
  2. fs stands for File System.
  3. Use writeFileSync() to create or replace a file.
  4. The first argument is the filename.
  5. The second argument is the content.
  6. Node.js writes the content to the file.
  7. A success message is displayed.

Question 4: How do you read a file using the fs module?

Problem

Read the content of notes.txt and display it in the terminal.

Solution

First make sure notes.txt contains:

Learning Node.js built-in modules.

Then create app.js:

const fs = require("fs");

const data = fs.readFileSync("notes.txt", "utf8");

console.log(data);

Output

Learning Node.js built-in modules.

Step-by-Step Explanation

  1. Import the fs module.
  2. Use readFileSync() to read the file.
  3. "notes.txt" is the file to read.
  4. "utf8" tells Node.js to return the content as readable text.
  5. Store the result in data.
  6. Display the content.

The fs module is one of the most commonly used built-in Node.js modules.


Question 5: How do you create a file path using the path module?

Problem

Create a file path using folder and filename values.

Solution

const path = require("path");

const filePath = path.join(
    "documents",
    "students",
    "data.txt"
);

console.log(filePath);

Output

On Windows, you may see:

documents\students\data.txt

On Linux or macOS, you may see:

documents/students/data.txt

Step-by-Step Explanation

  1. Import the path module.
  2. Use path.join().
  3. Pass the folder names.
  4. Pass the filename.
  5. Node.js creates the appropriate path for the operating system.
  6. Display the result.

Using path.join() is safer than manually joining paths with / or \.


Question 6: How do you get the filename and extension using the path module?

Problem

Given a file path, find its filename and file extension.

Solution

const path = require("path");

const filePath = "documents/student/profile.js";

console.log("Filename:", path.basename(filePath));
console.log("Extension:", path.extname(filePath));

Output

Filename: profile.js
Extension: .js

Step-by-Step Explanation

  1. Import the path module.
  2. Store the file path in filePath.
  3. path.basename() returns the last part of the path.
  4. path.extname() returns the file extension.
  5. Display both results.

This is useful when working with uploaded files or file-processing applications.


Question 7: How do you work with URLs using the url module?

Problem

Use the Node.js built-in URL class to read information from a URL.

Solution

const myUrl = new URL(
    "https://example.com/products?id=101"
);

console.log("Protocol:", myUrl.protocol);
console.log("Host:", myUrl.host);
console.log("Path:", myUrl.pathname);
console.log("Query:", myUrl.search);

Output

Protocol: https:
Host: example.com
Path: /products
Query: ?id=101

Step-by-Step Explanation

  1. Create a new URL object.
  2. Pass the complete URL.
  3. .protocol gives the protocol.
  4. .host gives the domain and port if present.
  5. .pathname gives the path.
  6. .search gives the query string.
  7. Display each value.

Node.js provides URL tools that are useful when working with web applications and APIs.


Question 8: How do you create and use an EventEmitter?

Problem

Create a custom event and run a function when that event occurs.

Solution

const EventEmitter = require("events");

const event = new EventEmitter();

event.on("welcome", () => {
    console.log("Welcome to Node.js!");
});

event.emit("welcome");

Output

Welcome to Node.js!

Step-by-Step Explanation

  1. Import EventEmitter from the built-in events module.
  2. Create a new EventEmitter object.
  3. Use .on() to listen for the welcome event.
  4. Add a function that should run when the event occurs.
  5. Use .emit() to trigger the event.
  6. The listener function runs.

Events are an important part of Node.js because many Node.js operations are event-driven.


Question 9: How do you check whether a file exists using the fs module?

Problem

Check whether notes.txt exists in the current folder.

Solution

const fs = require("fs");

const exists = fs.existsSync("notes.txt");

if (exists) {
    console.log("File exists.");
} else {
    console.log("File does not exist.");
}

Output

If the file exists:

File exists.

If the file does not exist:

File does not exist.

Step-by-Step Explanation

  1. Import the fs module.
  2. Use fs.existsSync().
  3. Pass the filename.
  4. The method returns true if the file exists.
  5. Otherwise, it returns false.
  6. Use an if...else statement to display the appropriate message.

Question 10: How do you combine multiple built-in modules in one Node.js program?

Problem

Create a small program that:

  • Creates a file path.
  • Writes information into a file.
  • Reads the file.
  • Displays the computer’s operating system.

Solution

const fs = require("fs");
const path = require("path");
const os = require("os");

const filePath = path.join(__dirname, "system-info.txt");

const information = `
Operating System: ${os.platform()}
Architecture: ${os.arch()}
`;

fs.writeFileSync(filePath, information);

const data = fs.readFileSync(filePath, "utf8");

console.log(data);

Output

The exact output depends on your computer.

For example:

Operating System: win32
Architecture: x64

Step-by-Step Explanation

  1. Import the fs module for file operations.
  2. Import the path module for creating a file path.
  3. Import the os module for operating system information.
  4. __dirname represents the directory of the current CommonJS file.
  5. path.join() creates the complete path.
  6. os.platform() gets the operating system.
  7. os.arch() gets the system architecture.
  8. fs.writeFileSync() writes the information into the file.
  9. fs.readFileSync() reads the file.
  10. console.log() displays the information.

Note: This example uses CommonJS syntax with require(). If your project is configured as an ES Module, the approach to accessing the current module’s directory is different.

Key Takeaways

  • Node.js includes many useful built-in modules.
  • Built-in modules do not normally need to be installed using npm.
  • The fs module is used for file system operations.
  • path helps create and work with file and directory paths.
  • os provides information about the operating system and hardware.
  • The url module provides tools for working with URLs.
  • The events module provides EventEmitter.
  • fs.writeFileSync() can create or overwrite a file.
  • fs.readFileSync() can read file content synchronously.
  • path.basename() returns the filename from a path.
  • path.extname() returns a file’s extension.
  • EventEmitter allows applications to create and respond to events.
  • Built-in modules are an important foundation for Node.js development.

FAQs

1. What are built-in modules in Node.js?

Built-in modules are modules that come with Node.js itself. They provide useful functionality such as file handling, path management, operating system information, events, URLs, and more.

2. Do I need to install Node.js built-in modules?

No. Built-in modules are included with Node.js, so you normally do not need to install them separately.

For example:

const fs = require("fs");

3. What is the fs module in Node.js?

The fs module stands for File System. It provides methods for creating, reading, writing, updating, and deleting files and directories.

4. What is the path module used for?

The path module helps you safely work with file and directory paths.

For example:

const path = require("path");

console.log(path.join("users", "data", "file.txt"));

5. What is the os module used for?

The os module provides information about the operating system and computer environment, such as the platform, architecture, CPU information, and memory information.

6. What is EventEmitter in Node.js?

EventEmitter is a feature provided by the built-in events module. It allows you to create events, listen for events, and trigger events using methods such as .on() and .emit().

7. Which Node.js built-in modules should beginners learn first?

Beginners should start with commonly used modules such as:

  • fs – File System
  • path – File and directory paths
  • os – Operating system information
  • events – Event handling
  • url – URL handling
  • http – Creating HTTP servers

After learning these, you can move on to more specialized Node.js modules.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top