Skip to content
jshacks.dev
Node.js

Node.js Built-In Modules Cheat Sheet

A quick reference to the Node.js built-in modules you reach for most, from fs and path to crypto, util and test, with runnable examples and exact output.

7 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Node.js, GitHub Actions, Cypress and Jest logos.

Node.js ships with a large standard library, and much of the time the module you need is already installed. The trouble is remembering which module holds what, and what its modern form looks like. This cheat sheet groups the built-in modules by job, shows the calls you use most, and points out the newer APIs that replace old npm packages. It targets Node.js 26 "Lithium", the LTS line since 2026-10-28, and most entries also hold on Node.js 24 and 22, which are in Maintenance. Every module is documented in the Node.js API reference, and importing with the node: prefix, as in node:fs, makes it explicit that you mean the built-in and not an npm package of the same name.

The map

JobModuleMain use
Filesnode:fs, node:fs/promisesread, write, list, watch, remove
Pathsnode:pathjoin, resolve, parse
Operating systemnode:osCPU count, memory, temp directory
Processnode:process, node:child_processenv, exit, spawn
Networknode:http, node:https, node:net, node:dnsservers, sockets
Streamsnode:stream, node:stream/promisespipe and transform data
Cryptonode:cryptohashes, HMAC, random, encryption
Utilitiesnode:utilparseArgs, promisify, inspect, styleText
Eventsnode:eventsEventEmitter, once
Timersnode:timers/promisesawait sleep
Testingnode:test, node:asserttests and assertions
Threadsnode:worker_threads, node:clusterparallel work
Datanode:sqlite, node:zlib, node:bufferstorage and compression
Observabilitynode:perf_hooks, node:diagnostics_channeltiming and tracing

Files: fs and fs/promises

Prefer the promise API for new code. It reads cleanly with await, and it does not block the event loop the way the Sync functions do. The most useful calls are readFile, writeFile, appendFile, readdir, stat, mkdir with { recursive: true }, rm with { recursive: true, force: true }, cp for copying trees, access for permission checks and watch for change events. Use the Sync forms only at startup or in scripts, where blocking is harmless. For large files, use createReadStream rather than loading everything into memory, or readFile on a file you know is small.

Paths: path

path.join glues segments with the right separator and normalizes ... path.resolve produces an absolute path, starting from the current directory when needed. path.parse splits a path into pieces, and path.extname and path.basename pick out single parts. In ES modules, use import.meta.dirname and import.meta.filename instead of the old __dirname.

path-demo.jsJavaScript
import path from "node:path";

const parsed = path.parse("/home/ana/app/report.final.csv");
console.log(parsed.name, parsed.ext);
console.log(path.join("/srv", "app", "..", "data", "x.json"));
console.log(path.basename("/srv/app/index.js", ".js"));
console.log(path.extname("archive.tar.gz"));
Text
report.final .csv
/srv/data/x.json
index
.gz

Note that extname returns only the last extension, so a .tar.gz file gives .gz. On Windows, path.win32 and path.posix give you each flavor explicitly, which helps when you write code that handles paths from another platform.

Command-line arguments: util.parseArgs

parseArgs replaces a small argument-parsing package for most scripts. You declare the options and their types, and it returns values and positional arguments. By default it throws on unknown options, which is usually what you want.

args-demo.jsJavaScript
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  args: ["--port", "8080", "-v", "input.txt"],
  options: {
    port: { type: "string" },
    verbose: { type: "boolean", short: "v" },
  },
  allowPositionals: true,
});

console.log(values.port, values.verbose, positionals);
Text
8080 true [ 'input.txt' ]

Leave out the args key and it reads process.argv for you. Numbers arrive as strings, so convert them yourself.

Hashing and random data: crypto

createHash makes digests, createHmac signs data with a secret, randomUUID creates version 4 identifiers and randomBytes produces unpredictable bytes for tokens. timingSafeEqual compares secrets without leaking timing. For passwords, use scrypt, which is built in, or a dedicated password hashing library, and never a plain hash.

hash-demo.jsJavaScript
import { createHash, createHmac } from "node:crypto";

const digest = createHash("sha256").update("hello").digest("hex");
console.log(digest.slice(0, 16));

const mac = createHmac("sha256", "secret").update("hello").digest("hex");
console.log(mac.length);
Text
2cf24dba5fb0a30e
64

A SHA-256 digest is 32 bytes, which is 64 hexadecimal characters. The first sixteen characters of the digest of hello are the same on every machine, which is why this sample's output is stable.

URLs and encoding: URL, URLSearchParams, Buffer

URL and URLSearchParams are globals in Node.js, so no import is needed, and they follow the web standard. Use them instead of the legacy url.parse. Buffer handles binary data, with Buffer.from(string, "base64") and buffer.toString("hex") for conversions. TextEncoder and TextDecoder are also global.

url-demo.jsJavaScript
const url = new URL("https://example.com/search?q=node&page=2");
console.log(url.hostname, url.searchParams.get("q"));
url.searchParams.set("page", "3");
console.log(url.search);
console.log(Buffer.from("hi").toString("base64"));
Text
example.com node
?q=node&page=3
aGk=

Events and timers

EventEmitter from node:events is the base for streams, servers and many libraries. events.once(emitter, "ready") returns a promise for the next event, which turns callback code into await. From node:timers/promises, setTimeout returns a promise, so a sleep is await setTimeout(100). It also offers setInterval as an async iterator and scheduler.wait.

Streams

Use pipeline from node:stream/promises to connect streams, since it handles errors and cleanup, which a bare .pipe() does not. Typical uses are copying a file with createReadStream into createWriteStream, compressing with zlib.createGzip() in the middle, or processing a large file line by line with readline. Web streams, ReadableStream and friends, are available as globals, and Readable.fromWeb and toWeb convert between the two kinds.

Testing and assertions

node:test provides test, describe, it, hooks, mocking with mock, snapshot support and coverage with --experimental-test-coverage. Run it with node --test. node:assert/strict gives equal, deepEqual, throws, rejects and friends in strict mode, which compares with strict equality and is the version to import. Because test output includes durations, it varies from run to run, so compare exit codes rather than text in scripts.

Processes and the system

process.env, process.argv, process.exit, process.on("SIGTERM"), process.memoryUsage() and process.hrtime.bigint() cover most needs. child_process.spawn runs a command and streams its output, execFile runs a command and returns the output without a shell, and exec runs through a shell, which is a risk if you include user input. os.cpus(), os.totalmem(), os.tmpdir() and os.EOL describe the machine.

Threads, compression, data

worker_threads runs JavaScript in parallel threads with message passing and shared memory. zlib handles gzip, deflate and brotli. node:sqlite provides an embedded SQLite database, and you should check the stability index in the docs before relying on it. perf_hooks offers performance.now() and PerformanceObserver for timing, and diagnostics_channel lets libraries publish events that monitoring tools subscribe to.

Quick recipes

A few patterns come up so often that they are worth memorizing. To read a JSON file, JSON.parse(await readFile(path, "utf8")) from fs/promises. To list files in a directory with their types, readdir(dir, { withFileTypes: true }) returns entries that know whether they are files or folders, which saves a stat call for each one. To wait for an event once, await once(emitter, "ready") from node:events. To run a command and capture its output, execFile from child_process, wrapped with util.promisify, which returns stdout and stderr as strings, and which avoids a shell. To measure a duration, performance.now() for milliseconds with fractions, or process.hrtime.bigint() for nanoseconds as a bigint. To copy a directory, cp(src, dest, { recursive: true }).

A last habit helps: when you need something and are about to install a package, search the API reference first. The index page at nodejs.org/api lists every module, and the sidebar of each page lists its functions, so a two-minute look often replaces a dependency. The reference also marks when each API was added, which tells you whether it exists on the Node.js version you run, so you do not write code that fails on an older Maintenance release.

Where this cheat sheet stops

This is a map and not a manual. Each module has more options than fit here, and some are experimental, so read the stability index at the top of each documentation page. Behavior on Windows differs in paths, signals and file permissions. Examples print stable values by avoiding clocks, random numbers and process ids. The list also leaves out rarely needed modules such as repl, tls, dgram and readline, which are documented in the same reference.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.