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
- Import the built-in
osmodule usingrequire(). os.platform()returns information about the operating system.os.arch()returns the CPU architecture.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
- Import the
osmodule. os.cpus()returns information about the available CPU cores..lengthcounts the returned CPU entries.- Store the number in
cpuCount. - 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
- Import the
fsmodule. fsstands for File System.- Use
writeFileSync()to create or replace a file. - The first argument is the filename.
- The second argument is the content.
- Node.js writes the content to the file.
- 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
- Import the
fsmodule. - Use
readFileSync()to read the file. "notes.txt"is the file to read."utf8"tells Node.js to return the content as readable text.- Store the result in
data. - 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
- Import the
pathmodule. - Use
path.join(). - Pass the folder names.
- Pass the filename.
- Node.js creates the appropriate path for the operating system.
- 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
- Import the
pathmodule. - Store the file path in
filePath. path.basename()returns the last part of the path.path.extname()returns the file extension.- 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
- Create a new
URLobject. - Pass the complete URL.
.protocolgives the protocol..hostgives the domain and port if present..pathnamegives the path..searchgives the query string.- 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
- Import
EventEmitterfrom the built-ineventsmodule. - Create a new
EventEmitterobject. - Use
.on()to listen for thewelcomeevent. - Add a function that should run when the event occurs.
- Use
.emit()to trigger the event. - 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
- Import the
fsmodule. - Use
fs.existsSync(). - Pass the filename.
- The method returns
trueif the file exists. - Otherwise, it returns
false. - Use an
if...elsestatement 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
- Import the
fsmodule for file operations. - Import the
pathmodule for creating a file path. - Import the
osmodule for operating system information. __dirnamerepresents the directory of the current CommonJS file.path.join()creates the complete path.os.platform()gets the operating system.os.arch()gets the system architecture.fs.writeFileSync()writes the information into the file.fs.readFileSync()reads the file.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
fsmodule is used for file system operations. pathhelps create and work with file and directory paths.osprovides information about the operating system and hardware.- The
urlmodule provides tools for working with URLs. - The
eventsmodule providesEventEmitter. 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.EventEmitterallows 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 Systempath– File and directory pathsos– Operating system informationevents– Event handlingurl– URL handlinghttp– 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.
