Node.js Core Modules
Node.js Learning Material

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.

OSPathDNS NetDomain

1OS Module

Operating System-based utility modules for Node.js are provided by the OS module.

Basic syntax and example
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.");
Common methods
MethodDescription
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).
↑ Back to top

2Path Module

The path module in Node.js is used for transforming and handling various file paths.

Syntax and introductory example
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));
notes.txt

Remove extension:

console.log(path.basename(file, ".txt"));
notes

2. path.dirname()

Returns the directory name.

const path = require("path");
const file = "C:\\Users\\Admin\\notes.txt";
console.log(path.dirname(file));
C:\Users\Admin

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"));
.pdf .png .js

4. path.join()

Joins path segments correctly.

const path = require("path");
const fullPath = path.join("Students", "Avinash", "marks.txt");
console.log(fullPath);
Windows OutputStudents\Avinash\marks.txt
Linux OutputStudents/Avinash/marks.txt

5. path.resolve()

Returns an absolute path.

const path = require("path");
console.log(path.resolve("data.txt"));
C:\NodeProject\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);
{ root: 'C:\\', dir: 'C:\\Users\\Admin', base: 'report.pdf', ext: '.pdf', name: 'report' }

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));
C:\Users\Admin\report.pdf

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"));
true false

9. path.normalize()

Removes unnecessary separators.

const path = require("path");
console.log(path.normalize("folder//subfolder///file.txt"));
folder\subfolder\file.txt (on Windows)

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));
Projects\Node

Real-Time Example: Reading a File

Suppose your project structure is:

Project │ ├── app.js ├── data │ └── students.txt
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);
});
Here:
  • __dirname gives the current directory.
  • path.join() creates the correct file path.
  • fs.readFile() reads the file.

Real-Time Example: Upload Folder

Project │ ├── uploads │ └── photo.jpg ├── server.js
const path = require("path");

const uploadPath = path.join(__dirname, "uploads", "photo.jpg");
console.log(uploadPath);
C:\Project\uploads\photo.jpg

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

Q1. Is the path module built into Node.js?
Answer: Yes. It is a core module, so no installation is needed.
Q2. Difference between path.join() and path.resolve()?
path.join()path.resolve()
Joins path segmentsReturns an absolute path
May return a relative pathAlways 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.txt

Path Module Summary

MethodPurpose
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
↑ Back to top

3DNS Module

The DNS module provides APIs for DNS resolution and hostname lookups using the operating system’s name resolution services.

Syntax
const dns = require('dns');
MethodPurpose
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);
});
Address of www.bakumar.online is "203.92.39.72" family: IPv4

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);
});
142.250.183.110 4

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);
});
[ '142.250.183.110', '142.250.183.111' ]

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);
});
[ '2404:6800:4007:80f::200e' ]

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);
});
[ 'dns.google' ]

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);
});
[ { exchange: 'gmail-smtp-in.l.google.com', priority: 5 }, { exchange: 'alt1.gmail-smtp-in.l.google.com', priority: 10 } ]

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);
});
[ ['v=spf1 include:_spf.google.com ~all'] ]

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);
});
[ 'ns1.google.com', 'ns2.google.com' ]

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);
});
[ 'github.com' ]

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}`);
});
openai.com IP Address: 104.xx.xx.xx

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);
  });
});
google.com -> 142.xxx.xxx.xxx github.com -> 140.xxx.xxx.xxx microsoft.com -> 20.xxx.xxx.xxx

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);
});
dns.google
↑ Back to top

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.

Syntax
const net = require('net');
MethodPurpose
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());
{ address: '127.0.0.1', family: 'IPv4', port: 3000 }

9. server.close()

Stops the server.

server.close();

Events

TypeEventMeaning
ServerconnectionTriggered when a client connects.
ServercloseTriggered when the server stops.
ServererrorTriggered when an error occurs.
SocketdataTriggered when data is received.
SocketendTriggered when the connection ends.
SocketcloseTriggered when the socket closes.
SocketerrorTriggered 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");
});
↑ Back to top

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.

Important: The source document notes that the Domain module is deprecated and should not be used in modern Node.js applications.

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.
Syntax
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...!'));
Output shown in the source material
Listener handled this error (Listener handles this) Error handled by dom_a (Dom_a handles this) Error handled by dom_b (Dom_b handles this) events.js:187 throw er; // Unhandled 'error' event Error: Exception message... ...stack trace...

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.
↑ Back to top

Quick Revision Summary

OSSystem information such as platform, architecture, memory, CPU and user details.
PathBuild, inspect, normalize and transform file-system paths.
DNSLook up hostnames, IP addresses and DNS record types.
NetCreate TCP servers and clients and exchange data through sockets.
DomainGroup asynchronous operations for error handling; Deprecated.