Node.js Core Modules
Node.js Core Modules provide built-in functionalities for handling system operations, file paths, networking, and error management in Node.js applications.
1OS Module
Operating System-based utility modules for Node.js are provided by the OS module.
const os = require('os');
// Display operating System type
console.log('Operating System type : ' + os.type());
// Display operating System platform
console.log('platform : ' + os.platform());
// Display total memory
console.log('total memory : ' + os.totalmem() + " bytes.");
// Display available memory
console.log('Available memory : ' + os.availmem() + " bytes.");| Method | Description |
|---|---|
| os.platform() | Returns the operating system platform. |
| os.arch() | Returns the CPU architecture. |
| os.hostname() | Returns the computer name (host name). |
| os.type() | Returns the operating system name. |
| os.release() | Returns the OS release version. |
| os.version() | Returns the operating system version. |
| os.uptime() | Returns the system uptime (seconds). |
| os.totalmem() | Returns total system memory (bytes). |
| os.freemem() | Returns free memory (bytes). |
| os.cpus() | Returns information about all CPU cores. |
| os.networkInterfaces() | Returns network interface information. |
| os.userInfo() | Returns details about the current user. |
| os.homedir() | Returns the user's home directory. |
| os.tmpdir() | Returns the temporary directory path. |
| os.endianness() | Returns the CPU byte order (BE or LE). |
2Path Module
The path module in Node.js is used for transforming and handling various file paths.
const path = require('path');
console.log('resolve:' + path.resolve('paths.js'));
console.log('extension:' + path.extname('paths.js'));Commonly Used Methods
1. path.basename()
Returns the last portion (file name) of a path.
const path = require("path");
const file = "C:\\Users\\Admin\\notes.txt";
console.log(path.basename(file));Remove extension:
console.log(path.basename(file, ".txt"));2. path.dirname()
Returns the directory name.
const path = require("path");
const file = "C:\\Users\\Admin\\notes.txt";
console.log(path.dirname(file));3. path.extname()
Returns the file extension.
const path = require("path");
console.log(path.extname("student.pdf"));
console.log(path.extname("image.png"));
console.log(path.extname("program.js"));4. path.join()
Joins path segments correctly.
const path = require("path");
const fullPath = path.join("Students", "Avinash", "marks.txt");
console.log(fullPath);Students\Avinash\marks.txtStudents/Avinash/marks.txt5. path.resolve()
Returns an absolute path.
const path = require("path");
console.log(path.resolve("data.txt"));If the current folder is C:\NodeProject, this is an example of the resulting absolute path.
6. path.parse()
Breaks a path into an object.
const path = require("path");
const details = path.parse("C:\\Users\\Admin\\report.pdf");
console.log(details);7. path.format()
Converts an object back into a path.
const path = require("path");
const obj = {
dir: "C:\\Users\\Admin",
name: "report",
ext: ".pdf"
};
console.log(path.format(obj));8. path.isAbsolute()
Checks whether a path is absolute.
const path = require("path");
console.log(path.isAbsolute("C:\\Users\\Admin"));
console.log(path.isAbsolute("notes.txt"));9. path.normalize()
Removes unnecessary separators.
const path = require("path");
console.log(path.normalize("folder//subfolder///file.txt"));10. path.relative()
Finds the relative path between two locations.
const path = require("path");
const from = "C:\\Users\\Admin";
const to = "C:\\Users\\Admin\\Projects\\Node";
console.log(path.relative(from, to));Real-Time Example: Reading a File
Suppose your project structure is:
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, "data", "students.txt");
fs.readFile(filePath, "utf8", (err, data) => {
if (err)
console.log(err);
else
console.log(data);
});__dirnamegives the current directory.path.join()creates the correct file path.fs.readFile()reads the file.
Real-Time Example: Upload Folder
const path = require("path");
const uploadPath = path.join(__dirname, "uploads", "photo.jpg");
console.log(uploadPath);Real-Time Example: Logging File
const path = require("path");
const logFile = path.join(__dirname, "logs", "app.log");
console.log(logFile);Useful for creating log files in a consistent location across operating systems.
Interview Questions
Answer: Yes. It is a core module, so no installation is needed.
| path.join() | path.resolve() |
|---|---|
| Joins path segments | Returns an absolute path |
| May return a relative path | Always resolves to an absolute path |
console.log(path.join("folder", "file.txt"));
// folder/file.txt
console.log(path.resolve("folder", "file.txt"));
// C:\CurrentFolder\folder\file.txtPath Module Summary
| Method | Purpose |
|---|---|
| basename() | Gets file name |
| dirname() | Gets directory |
| extname() | Gets file extension |
| join() | Joins path segments |
| resolve() | Creates an absolute path |
| parse() | Converts a path to an object |
| format() | Converts an object to a path |
| isAbsolute() | Checks if a path is absolute |
| normalize() | Cleans up path separators |
| relative() | Finds relative path between locations |
3DNS Module
The DNS module provides APIs for DNS resolution and hostname lookups using the operating system’s name resolution services.
const dns = require('dns');| Method | Purpose |
|---|---|
| lookup() | Get IP address from a hostname |
| resolve4() | Get IPv4 addresses |
| resolve6() | Get IPv6 addresses |
| reverse() | Get hostname from an IP address |
| resolveMx() | Get email (MX) records |
| resolveTxt() | Get TXT records |
| resolveNs() | Get name server records |
| resolveCname() | Get canonical (alias) name records |
Basic lookup example
const dns = require('dns');
// Store the web address
const website = 'bakumar.online';
// Call lookup function of DNS
dns.lookup(website, (err, address, family) => {
console.log('Address of %s is %j family: IPv%s',
website, address, family);
});1. dns.lookup()
Looks up the IP address of a hostname.
const dns = require("dns");
dns.lookup("google.com", (err, address, family) => {
if (err)
console.log(err);
else
console.log(address, family);
});Here: address is the IP address and family is the IP version (4 or 6).
2. dns.resolve4()
Returns all IPv4 addresses.
const dns = require("dns");
dns.resolve4("google.com", (err, addresses) => {
if (err)
console.log(err);
else
console.log(addresses);
});3. dns.resolve6()
Returns IPv6 addresses.
const dns = require("dns");
dns.resolve6("google.com", (err, addresses) => {
if (err)
console.log(err);
else
console.log(addresses);
});4. dns.reverse()
Converts an IP address into a hostname.
const dns = require("dns");
dns.reverse("8.8.8.8", (err, hostnames) => {
if (err)
console.log(err);
else
console.log(hostnames);
});5. dns.resolveMx()
Returns Mail Exchange (MX) records used by email servers.
const dns = require("dns");
dns.resolveMx("gmail.com", (err, addresses) => {
if (err)
console.log(err);
else
console.log(addresses);
});6. dns.resolveTxt()
Returns TXT records.
const dns = require("dns");
dns.resolveTxt("google.com", (err, records) => {
if (err)
console.log(err);
else
console.log(records);
});TXT records are commonly used for:
- SPF
- DKIM
- Domain verification
7. dns.resolveNs()
Returns Name Server (NS) records.
const dns = require("dns");
dns.resolveNs("google.com", (err, servers) => {
if (err)
console.log(err);
else
console.log(servers);
});8. dns.resolveCname()
Returns Canonical Name (CNAME) records.
const dns = require("dns");
dns.resolveCname("www.github.com", (err, addresses) => {
if (err)
console.log(err);
else
console.log(addresses);
});Real-Time Example 1: Website Availability Checker
const dns = require("dns");
const website = "openai.com";
dns.lookup(website, (err, address) => {
if (err)
console.log("Website not found");
else
console.log(`${website} IP Address: ${address}`);
});Real-Time Example 2: Network Diagnostic Tool
const dns = require("dns");
const websites = [
"google.com",
"github.com",
"microsoft.com"
];
websites.forEach(site => {
dns.lookup(site, (err, address) => {
if (err)
console.log(site + " not found");
else
console.log(site + " -> " + address);
});
});Real-Time Example 3: Email Domain Validation
const dns = require("dns");
dns.resolveMx("gmail.com", (err, records) => {
if (records)
console.log("Email server exists");
else
console.log("No mail server");
});Real-Time Example 4: Reverse DNS Lookup
const dns = require("dns");
dns.reverse("8.8.8.8", (err, hostnames) => {
if (err)
console.log(err);
else
console.log(hostnames);
});4Net Module
Net Module in Node.js is used for the creation of both client and server. Similar to DNS Module, this module also provides an asynchronous network wrapper.
const net = require('net');| Method | Purpose |
|---|---|
| createServer() | Creates a TCP server |
| createConnection() | Creates a TCP client |
| listen() | Starts the server |
| write() | Sends data |
| end() | Closes the connection gracefully |
| destroy() | Immediately terminates the connection |
| address() | Returns socket details |
| setTimeout() | Sets a timeout for the socket |
| close() | Stops the server |
1. net.createServer()
Creates a TCP server.
const net = require("net");
const server = net.createServer((socket) => {
console.log("Client Connected");
socket.write("Welcome to Node.js Server");
socket.end();
});
server.listen(3000, () => {
console.log("Server Running");
});2. server.listen()
Starts listening for client connections.
server.listen(5000, () => {
console.log("Listening on port 5000");
});3. net.createConnection()
Creates a TCP client.
const net = require("net");
const client = net.createConnection({
host: "localhost",
port: 3000
});
client.on("data", (data) => {
console.log(data.toString());
});4. socket.write()
Sends data to the client/server.
socket.write("Hello Client");5. socket.end()
Closes the connection.
socket.end();6. socket.destroy()
Immediately terminates the connection.
socket.destroy();7. socket.setTimeout()
Sets socket timeout.
socket.setTimeout(5000);8. socket.address()
Returns socket information.
console.log(socket.address());9. server.close()
Stops the server.
server.close();Events
| Type | Event | Meaning |
|---|---|---|
| Server | connection | Triggered when a client connects. |
| Server | close | Triggered when the server stops. |
| Server | error | Triggered when an error occurs. |
| Socket | data | Triggered when data is received. |
| Socket | end | Triggered when the connection ends. |
| Socket | close | Triggered when the socket closes. |
| Socket | error | Triggered on socket errors. |
Server-Side Example
// Require net module
const net = require("net");
const server = net.createServer((socket) => {
console.log("Client connected");
socket.on("data", (data) => {
console.log("Message from Client:", data.toString());
socket.write("Hello Client! Message received.");
});
socket.on("end", () => {
console.log("Client disconnected");
});
});
server.listen(5000, () => {
console.log("Server is running on port 5000");
});Client-Side Example
const net = require("net");
const client = new net.Socket();
client.connect(5000, "localhost", () => {
console.log("Connected to Server");
client.write("Hello Server!");
});
client.on("data", (data) => {
console.log("Message from Server:", data.toString());
client.end();
});
client.on("close", () => {
console.log("Connection closed");
});5Domain Module
The Domain module in Node.js is used to handle and intercept unhandled errors in asynchronous operations. It groups multiple I/O operations into a single context so that errors can be handled together.
Error Interception
Error interception can be performed in two ways:
- Internal Binding: The error emitter runs the code internally within the
run()method of a domain. - External Binding: The error emitter is explicitly added to the domain using the
add()method.
const domain = require('domain');The domain class provides a mechanism for routing unhandled exceptions and errors to the active domain object. It is considered a child class of EventEmitter.
Domain Example
const EventEmitter = require("events").EventEmitter;
const domain = require("domain");
const emit_a = new EventEmitter();
const dom_a = domain.create();
dom_a.on('error', function (err) {
console.log("Error handled by dom_a (" + err.message + ")");
});
dom_a.add(emit_a);
emit_a.on('error', function (err) {
console.log("listener handled this error (" + err.message + ")");
});
emit_a.emit('error', new Error('Listener handles this'));
emit_a.removeAllListeners('error');
emit_a.emit('error', new Error('Dom_a handles this'));
const dom_b = domain.create();
dom_b.on('error', function (err) {
console.log("Error handled by dom_b (" + err.message + ")");
});
dom_b.run(function () {
const emit_b = new EventEmitter();
emit_b.emit('error', new Error('Dom_b handles this'));
});
dom_a.remove(emit_a);
emit_a.emit('error', new Error('Exception message...!'));Advantages listed in the source
- Enhanced Debugging: Provides powerful tools for inspecting and debugging objects.
- Simplified Async Handling: Makes it easier to work with asynchronous code by converting callback-based APIs to promise-based ones.
- Flexible String Formatting: Allows dynamic and customizable string formatting.