❤ Like
🔖 Save
🔗 Share
Eric Hu
Eric Hu

Core Node.js Modules

@thedevspaceio

🟢 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


ModulePurpose
fsRead, write, and manage files.
pathBuild and parse file paths cross-platform.
httpCreate HTTP servers and clients.
eventsImplement the observer pattern with EventEmitter.
streamProcess data in chunks.
cryptoHashing, encryption, and random values.
osOperating system information.
processCurrent process info and environment variables.
urlParse and format URLs.
utilUtilities like promisify and inspect.

fs

Work with the file system. Promise-based API lives in fs/promises.

js
import { readFile, writeFile, mkdir, readdir, stat } from "fs/promises";

Read the contents of a file as a string.

js
const data = await readFile("config.json", "utf-8");

Write data to a file, creating or overwriting it.

js
await writeFile("output.txt", "Hello");

Create a new directory, optionally creating parent directories.

js
// 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.

js
const files = await readdir("./src");

Get metadata about a file or directory.

js
const stats = await stat("file.txt");
stats.isFile(); // true
stats.size; // bytes

path

Build file paths that work on every operating system.

js
import path from "path";

Join path segments using the correct separator for the current OS.

js
path.join("/users", "ada", "file.txt");
// "/users/ada/file.txt" on Linux and macOS
// "\users\ada\file.txt" on Windows

Resolve a sequence of paths to an absolute path from the current working directory.

js
path.resolve("src", "index.js");
// "/home/user/project/src/index.js"

Extract the filename portion from a file path.

js
path.basename("/users/ada/file.txt");
// "file.txt"

Extract the directory portion from a file path.

js
path.dirname("/users/ada/file.txt");
// "/users/ada"

Get the file extension from a file path.

js
path.extname("file.txt");
// ".txt"

Parse a file path into an object with root, dir, base, ext, and name properties.

js
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.

js
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.

js
import { EventEmitter } from "events";
 
const emitter = new EventEmitter();

Register a listener that runs every time an event is emitted.

js
emitter.on("order", (order) => console.log("New order:", order.id));

Register a listener that runs only once and then automatically removes itself.

js
emitter.once("init", () => console.log("Runs once"));

Emit an event to trigger all registered listeners with optional data.

js
emitter.emit("order", { id: 42 });

Remove a specific listener from an event.

js
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.

js
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.

js
const readable = createReadStream("input.txt");

Create a writable stream to write data to a destination.

js
import { createWriteStream } from "fs";
const writable = createWriteStream("output.txt");

Create a transform stream that modifies data passing through it.

js
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.

js
readable.pipe(upperCase).pipe(writable);

Pipe a readable stream directly to the console output.

js
readable.pipe(process.stdout);

Use the 'data' event to process chunks individually without piping.

js
readable.on("data", (chunk) => {
  console.log(`Received ${chunk.length} bytes`);
});
 
readable.on("end", () => {
  console.log("No more data");
});

Handle stream errors to prevent crashes.

js
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.).

js
import { createHash } from "crypto";
 
const hash = createHash("sha256").update("data").digest("hex");
// "3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7"

Generate cryptographically secure random bytes for API keys, tokens, or salts.

js
import { randomBytes } from "crypto";
 
const token = randomBytes(32).toString("hex");
// "f4a8d7c2b0e9f6a1b3c8d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5"

Generate a secure random UUID v4 for unique identifiers.

js
import { randomUUID } from "crypto";
 
const id = randomUUID();
// "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

Hash passwords asynchronously with scrypt.

js
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.

js
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.

js
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.

js
import os from "os";

Get the number of CPU cores available on the machine.

js
os.cpus().length; // 8

Get the total system memory in bytes.

js
os.totalmem(); // 17179869184 (16GB)

Get the amount of free system memory in bytes.

js
os.freemem(); // 4294967296 (4GB)

Get the machine's hostname.

js
os.hostname(); // "macbook-pro.local"

Get the operating system platform.

js
os.platform(); // "linux", "darwin", or "win32"

Get the operating system release version.

js
os.release(); // "22.6.0"

Get system uptime in seconds.

js
os.uptime(); // 86400 (1 day)

Get network interface information.

js
os.networkInterfaces();
// { en0: [ { address: '192.168.1.100', ... } ] }

Get the user's home directory.

js
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.

js
process.env.NODE_ENV; // "production" or "development"

Read command-line arguments passed to the script.

js
process.argv; // ["node", "script.js", "--flag", "value"]

Get the current process ID.

js
process.pid; // 12345

Get the current working directory where the script is executed.

js
process.cwd(); // "/home/user/project"

Exit the process immediately with an optional status code.

js
process.exit(1); // 0 = success, non-zero = error

Listen for process events like termination signals.

js
process.on("SIGTERM", () => {
  console.log("Received SIGTERM, cleaning up...");
  gracefulShutdown();
});

Listen for uncaught exceptions to prevent crashes.

js
process.on("uncaughtException", (err) => {
  console.error("Unhandled error:", err.message);
});

Get memory usage of the Node.js process.

js
process.memoryUsage();
// { rss: 50.5 MB, heapTotal: 20 MB, heapUsed: 15 MB, external: 2 MB }

Get the Node.js version.

js
process.version; // "v22.0.0"

Get the current platform the process is running on.

js
process.platform; // "linux", "darwin", or "win32"

Set an environment variable for the current process only.

js
process.env.MY_VAR = "some-value";

Get the time spent in user and system CPU time.

js
process.cpuUsage();
// { user: 150000, system: 30000 } (microseconds)

Measure the elapsed time between two points.

js
process.hrtime.bigint(); // Returns high-resolution timestamp in nanoseconds

Handle before-exit events to perform cleanup.

js
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.

js
import { URL } from "url";

Create a URL object from a string to access its components.

js
const url = new URL("https://example.com/users?page=2");

Get the hostname portion of the URL.

js
url.hostname; // "example.com"

Get the path portion of the URL.

js
url.pathname; // "/users"

Access query parameters using the searchParams API.

js
url.searchParams.get("page"); // "2"

Set or modify query parameters on a URL.

js
url.searchParams.set("sort", "asc");
url.toString(); // "https://example.com/users?page=2&sort=asc"

Get the full URL as a string.

js
url.href; // "https://example.com/users?page=2"

Parse legacy URLs using the deprecated url.parse() (prefer the URL class).

js
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.

js
const myUrl = new URL("/path", "https://example.com");
// "https://example.com/path"

Get the search parameters as a key-value object.

js
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.

js
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).

js
import { inspect } from "util";
inspect(obj, { depth: null, colors: true }); // Full depth with colors

Inspect without formatting limitations to see hidden properties.

js
console.log(inspect(complexObject, { showHidden: true, depth: null }));

Format a string with placeholders (similar to printf).

js
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.

js
import { types } from "util";
types.isDate(new Date()); // true
types.isMap(new Map()); // true
types.isRegExp(/regex/); // true

Parse a string to a JavaScript value (like JSON.parse but more flexible).

js
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.

js
import { callbackify } from "util";
const fn = callbackify(async () => "result");
// Converts async function to error-first callback style

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io