Node.js Built-in Modules
Learn how Node.js built-in modules provide functionality for file handling, path operations, operating-system information, HTTP servers, events and URL processing.
1. What Are Built-in Modules?
Built-in modules are modules provided by Node.js itself. They provide functionality for common programming tasks without requiring us to install a separate package for each feature.
For example, when an application needs to read a file, it can use
the fs module. When it needs to work with file paths,
it can use the path module. A server can use the
http module to receive requests and send responses.
Advantages of Built-in Modules
- No separate package installation is required for these modules.
- They provide ready-to-use functionality.
- They reduce the amount of code we need to write ourselves.
- They help developers work with files, operating-system information and networking.
2. Common Built-in Modules
| Module | Purpose | Example Use |
|---|---|---|
fs |
File system operations | Read or write a file |
path |
File and directory paths | Join path segments |
os |
Operating-system information | Get platform or CPU information |
http |
HTTP server functionality | Receive HTTP requests |
events |
Event-driven programming | Emit and handle custom events |
url |
URL processing | Read URL pathname or query parameters |
3. How Built-in Modules Work
A Node.js application imports the required built-in module, calls its methods and uses the returned values or results.
Node.js Application
Identify the required functionality.
Import Built-in Module
const path = require("node:path");
Call a Module Method
path.join("folder", "file.txt");
Use the Result
The application receives the resulting path.
4. fs Module — File System
The fs module allows a Node.js application to
interact with the file system. It supports operations such as
reading, writing, appending and deleting files.
Example: Write a File
The writeFileSync() method writes content to a file
synchronously. If the file does not exist, it normally creates it.
If it already exists, its contents are replaced.
const fs = require("node:fs");
fs.writeFileSync("message.txt", "Welcome to Node.js!");
console.log("File created successfully.");
Expected Output
File created successfully.
A file named message.txt is created in the current
working directory if it does not already exist. Its content is:
Welcome to Node.js!
Example: Read a File
const fs = require("node:fs");
const content = fs.readFileSync("message.txt", "utf8");
console.log(content);
Expected Output
Welcome to Node.js!
fs.readFile() are preferable.
5. path Module — File Paths
The path module provides utilities for working with
file and directory paths. It helps build paths using the correct
separators for the operating system.
Example: Join Path Segments
const path = require("node:path");
const filePath = path.join("students", "details", "student.txt");
console.log(filePath);
Expected Output on Windows
students\details\student.txt
Example: Get File Extension
const path = require("node:path");
const fileName = "student.js";
console.log(path.extname(fileName));
Expected Output
.js
The exact path separator depends on the operating system.
path.join() builds a path using the platform's
normal separator.
6. os Module — Operating System
The os module provides information about the
operating system on which Node.js is running.
Example: Get Platform and Architecture
const os = require("node:os");
console.log("Platform:", os.platform());
console.log("Architecture:", os.arch());
Example Output on a Typical 64-bit Windows Computer
Platform: win32 Architecture: x64
The actual output depends on the computer running the program. Other operating systems can return different platform values.
Example: Get CPU Information
const os = require("node:os");
console.log("CPU Information:");
console.log(os.cpus());
The output contains CPU details and can be lengthy because it depends on the machine's processor configuration.
7. http Module — Create a Server
The http module provides functionality for creating
HTTP servers. A server can receive requests and send responses
to clients.
Example: Create a Simple HTTP Server
const http = require("node:http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Welcome to Node.js Server!");
});
server.listen(3000, () => {
console.log("Server is running on port 3000.");
});
Expected Terminal Output
Server is running on port 3000.
Response Body
Welcome to Node.js Server!
Save the code in server.js and run it using
node server.js. The server listens on port
3000. A client can then send a request to the
server on that port.
Ctrl + C in the
terminal when you finish.
8. events Module — Event Handling
Node.js uses an event-driven programming model. The
events module provides the EventEmitter
class, which lets us define and handle custom events.
Example: Create a Custom Event
const EventEmitter = require("node:events");
const eventEmitter = new EventEmitter();
eventEmitter.on("welcome", () => {
console.log("Welcome event executed!");
});
eventEmitter.emit("welcome");
Expected Output
Welcome event executed!
Explanation
EventEmitteris imported from the built-in module.- An event emitter object is created.
on()registers a listener for thewelcomeevent.emit()triggers that event.- The registered callback displays the message.
9. url Module — URL Processing
The URL class allows us to parse and work with
URLs, including their hostnames, pathnames and query parameters.
Example: Read URL Information
const { URL } = require("node:url");
const myUrl = new URL(
"https://example.com/students?course=nodejs"
);
console.log("Hostname:", myUrl.hostname);
console.log("Pathname:", myUrl.pathname);
console.log("Course:", myUrl.searchParams.get("course"));
Expected Output
Hostname: example.com Pathname: /students Course: nodejs
The URL is parsed as data; this example does not send a network request to the host.
10. Built-in Modules in an Application
Different modules can support different parts of the same Node.js application. The application selects the module that matches the task it needs to perform.
Node.js Program
Choose the required operation.
fs
Read and write files.
path
Build and inspect paths.
os
Inspect the host system.
http
Handle HTTP requests.
events
Register and emit events.
url
Read URL components.
The selected module provides the required functionality.
11. CommonJS and ES Module Import Syntax
Built-in modules can be used with CommonJS or ES Module syntax, depending on how the application is configured.
| Module | CommonJS | ES Modules |
|---|---|---|
| File system | const fs = require("node:fs"); |
import fs from "node:fs"; |
| Path | const path = require("node:path"); |
import path from "node:path"; |
| Operating system | const os = require("node:os"); |
import os from "node:os"; |
| HTTP | const http = require("node:http"); |
import http from "node:http"; |
node: prefix explicitly
identifies a Node.js built-in module. It can be used with
built-in module imports in supported Node.js versions.
12. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Trying to install a built-in module separately. | Use the built-in module supplied by Node.js. |
| Using an incorrect import syntax. | Check whether the file uses CommonJS or ES Modules. |
| Reading a file that does not exist. | Ensure the file exists at the expected location and handle errors. |
| Assuming every operating system produces identical output. | Remember that path and OS information can vary by platform. |
| Assuming an HTTP server stops automatically. | Keep the server running during testing and stop it when finished. |
13. Practice Tasks
Task 1: File System
Use the fs module to create a file named
student.txt, write a student name into it,
and read the content.
Student file created.
Student: Samadhan
Task 2: Path Module
Use the path module to join a folder name
with a filename and display the file extension.
.js
Task 3: Events Module
Create a custom event named studentRegistered.
Register an event listener and emit the event.
Student registered successfully!
Task 4: Operating System
Use the os module to display the operating-system
platform and CPU architecture of your computer.
Summary
Node.js built-in modules provide ready-to-use functionality for common application tasks. The fs module handles file operations, path manages file paths, os provides operating-system information, http supports HTTP servers, events enables custom event handling, and url helps process URL components. These modules can be imported using CommonJS or ES Module syntax, depending on the project configuration. Understanding built-in modules helps developers build organized Node.js applications without installing separate packages for these core features.