
Core Node.js Modules
🟢 10 Core Node.js Modules You Should Know
Node.js ships with built-in modules for files, paths, HTTP, events, and more. This cheatsheet covers the core modules you will use most.
✅ fs : Read, write, and manage files.
✅ path : Build and parse file paths cross-platform.
✅ http : Create HTTP servers and clients.
✅ events : Implement the observer pattern with EventEmitter.
✅ stream : Process data in chunks.
✅ crypto : Hashing, encryption, and random values.
✅ os : Operating system information.
✅ process : Current process info and environment variables.
✅ url : Parse and format URLs.
✅ util : Utilities like promisify and inspect.
#nodejs #javascript #modules #backend #webdev #coding #tips
| Module | Purpose |
|---|---|
fs | Read, write, and manage files. |
path | Build and parse file paths cross-platform. |
http | Create HTTP servers and clients. |
events | Implement the observer pattern with EventEmitter. |
stream | Process data in chunks. |
crypto | Hashing, encryption, and random values. |
os | Operating system information. |
process | Current process info and environment variables. |
url | Parse and format URLs. |
util | Utilities like promisify and inspect. |
fs
Work with the file system. Promise-based API lives in fs/promises.
import { readFile, writeFile, mkdir, readdir, stat } from "fs/promises";Read the contents of a file as a string.
const data = await readFile("config.json", "utf-8");Write data to a file, creating or overwriting it.
await writeFile("output.txt", "Hello");Create a new directory, optionally creating parent directories.
// Creates just "uploads"
await mkdir("uploads");
// Creates "images", then "2024", then "photos" inside it
await mkdir("images/2024/photos", { recursive: true });Get a list of files and folders in a directory.
const files = await readdir("./src");Get metadata about a file or directory.
const stats = await stat("file.txt");
stats.isFile(); // true
stats.size; // bytespath
Build file paths that work on every operating system.
import path from "path";Join path segments using the correct separator for the current OS.
path.join("/users", "ada", "file.txt");
// "/users/ada/file.txt" on Linux and macOS
// "\users\ada\file.txt" on WindowsResolve a sequence of paths to an absolute path from the current working directory.
path.resolve("src", "index.js");
// "/home/user/project/src/index.js"Extract the filename portion from a file path.
path.basename("/users/ada/file.txt");
// "file.txt"Extract the directory portion from a file path.
path.dirname("/users/ada/file.txt");
// "/users/ada"Get the file extension from a file path.
path.extname("file.txt");
// ".txt"Parse a file path into an object with root, dir, base, ext, and name properties.
path.parse("/users/ada/file.txt");
// {
// root: "/",
// dir: "/users/ada",
// base: "file.txt",
// ext: ".txt",
// name: "file",
// }http
Create a web server without a framework.
import { createServer } from "http";
const server = createServer((req, res) => {
if (req.url === "/api/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok" }));
return;
}
res.writeHead(404);
res.end("Not found");
});
server.listen(3000, () => console.log("Listening on :3000"));In practice, use Express or other web frameworks. The http module powers them underneath.
events
Implement publish-subscribe with EventEmitter.
import { EventEmitter } from "events";
const emitter = new EventEmitter();Register a listener that runs every time an event is emitted.
emitter.on("order", (order) => console.log("New order:", order.id));Register a listener that runs only once and then automatically removes itself.
emitter.once("init", () => console.log("Runs once"));Emit an event to trigger all registered listeners with optional data.
emitter.emit("order", { id: 42 });Remove a specific listener from an event.
emitter.off("order", handler);Many core modules (stream, server) extend EventEmitter.
stream
Process data in chunks instead of loading everything into memory.
Ideal for large files, network requests, or any scenario where data arrives incrementally.
import { createReadStream } from "fs";
import { Transform } from "stream";There are four types of streams:
- Readable - for reading data
- Writable - for writing data
- Duplex - for both reading and writing (e.g., network sockets)
- Transform - a Duplex that modifies data between reading and writing
Create a readable stream to read data from a source in chunks.
const readable = createReadStream("input.txt");Create a writable stream to write data to a destination.
import { createWriteStream } from "fs";
const writable = createWriteStream("output.txt");Create a transform stream that modifies data passing through it.
const upperCase = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});Piping is when you connect a readable stream to a writable or transform stream, allowing data to flow automatically.
readable.pipe(upperCase).pipe(writable);Pipe a readable stream directly to the console output.
readable.pipe(process.stdout);Use the 'data' event to process chunks individually without piping.
readable.on("data", (chunk) => {
console.log(`Received ${chunk.length} bytes`);
});
readable.on("end", () => {
console.log("No more data");
});Handle stream errors to prevent crashes.
readable.on("error", (err) => {
console.error("Stream error:", err.message);
});crypto
This module provides cryptographic functionality for securing data, hash generation, random value creation, and password hashing.
Create a hash digest of data using a specified algorithm (SHA-256, SHA-512, MD5, etc.).
import { createHash } from "crypto";
const hash = createHash("sha256").update("data").digest("hex");
// "3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7"Generate cryptographically secure random bytes for API keys, tokens, or salts.
import { randomBytes } from "crypto";
const token = randomBytes(32).toString("hex");
// "f4a8d7c2b0e9f6a1b3c8d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5"Generate a secure random UUID v4 for unique identifiers.
import { randomUUID } from "crypto";
const id = randomUUID();
// "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"Hash passwords asynchronously with scrypt.
import { randomBytes, scrypt } from "crypto";
const salt = randomBytes(16).toString("hex");
scrypt(password, salt, 64, (err, key) => {
const hashedPassword = key.toString("hex");
});Hash passwords synchronously with scrypt.
import { scryptSync } from "crypto";
const key = scryptSync(password, salt, 64).toString("hex");Create an HMAC (Hash-based Message Authentication Code) for verifying message integrity and authenticity.
import { createHmac } from "crypto";
const hmac = createHmac("sha256", "secret-key").update("message").digest("hex");os
Get system-level information like CPU, memory, and operating system details.
import os from "os";Get the number of CPU cores available on the machine.
os.cpus().length; // 8Get the total system memory in bytes.
os.totalmem(); // 17179869184 (16GB)Get the amount of free system memory in bytes.
os.freemem(); // 4294967296 (4GB)Get the machine's hostname.
os.hostname(); // "macbook-pro.local"Get the operating system platform.
os.platform(); // "linux", "darwin", or "win32"Get the operating system release version.
os.release(); // "22.6.0"Get system uptime in seconds.
os.uptime(); // 86400 (1 day)Get network interface information.
os.networkInterfaces();
// { en0: [ { address: '192.168.1.100', ... } ] }Get the user's home directory.
os.homedir(); // "/Users/username"process
Access and interact with the current Node.js process, including environment, arguments, and lifecycle events. process is globally available, no import needed.
Access environment variables from the shell.
process.env.NODE_ENV; // "production" or "development"Read command-line arguments passed to the script.
process.argv; // ["node", "script.js", "--flag", "value"]Get the current process ID.
process.pid; // 12345Get the current working directory where the script is executed.
process.cwd(); // "/home/user/project"Exit the process immediately with an optional status code.
process.exit(1); // 0 = success, non-zero = errorListen for process events like termination signals.
process.on("SIGTERM", () => {
console.log("Received SIGTERM, cleaning up...");
gracefulShutdown();
});Listen for uncaught exceptions to prevent crashes.
process.on("uncaughtException", (err) => {
console.error("Unhandled error:", err.message);
});Get memory usage of the Node.js process.
process.memoryUsage();
// { rss: 50.5 MB, heapTotal: 20 MB, heapUsed: 15 MB, external: 2 MB }Get the Node.js version.
process.version; // "v22.0.0"Get the current platform the process is running on.
process.platform; // "linux", "darwin", or "win32"Set an environment variable for the current process only.
process.env.MY_VAR = "some-value";Get the time spent in user and system CPU time.
process.cpuUsage();
// { user: 150000, system: 30000 } (microseconds)Measure the elapsed time between two points.
process.hrtime.bigint(); // Returns high-resolution timestamp in nanosecondsHandle before-exit events to perform cleanup.
process.on("beforeExit", (code) => {
console.log("Process about to exit with code:", code);
});url
Parse, construct, and manipulate URLs easily using the built-in URL class.
import { URL } from "url";Create a URL object from a string to access its components.
const url = new URL("https://example.com/users?page=2");Get the hostname portion of the URL.
url.hostname; // "example.com"Get the path portion of the URL.
url.pathname; // "/users"Access query parameters using the searchParams API.
url.searchParams.get("page"); // "2"Set or modify query parameters on a URL.
url.searchParams.set("sort", "asc");
url.toString(); // "https://example.com/users?page=2&sort=asc"Get the full URL as a string.
url.href; // "https://example.com/users?page=2"Parse legacy URLs using the deprecated url.parse() (prefer the URL class).
import { parse } from "url";
const parsed = parse("https://example.com/path?query=1");
// { protocol: 'https:', hostname: 'example.com', pathname: '/path', ... }Build a URL from component parts.
const myUrl = new URL("/path", "https://example.com");
// "https://example.com/path"Get the search parameters as a key-value object.
Object.fromEntries(url.searchParams);
// { page: '2', sort: 'asc' }util
Access a collection of handy utility functions for common tasks like converting callbacks and inspecting objects.
Convert a callback-based function into a promise-based one.
import fs from "fs";
import { promisify } from "util";
const readFile = promisify(fs.readFile);
const data = await readFile("file.txt", "utf-8");Inspect an object for deep, formatted logging (more readable than console.log).
import { inspect } from "util";
inspect(obj, { depth: null, colors: true }); // Full depth with colorsInspect without formatting limitations to see hidden properties.
console.log(inspect(complexObject, { showHidden: true, depth: null }));Format a string with placeholders (similar to printf).
import { format } from "util";
format("Hello %s, you have %d messages", "Alice", 5);
// "Hello Alice, you have 5 messages"Get the type of a value as a normalized string.
import { types } from "util";
types.isDate(new Date()); // true
types.isMap(new Map()); // true
types.isRegExp(/regex/); // trueParse a string to a JavaScript value (like JSON.parse but more flexible).
import { parseArgs } from "util";
const { values, positionals } = parseArgs({
args: process.argv,
options: { verbose: { type: "boolean" } },
});Create a callback that ignores errors and passes through values.
import { callbackify } from "util";
const fn = callbackify(async () => "result");
// Converts async function to error-first callback styleFull-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.