Node.js Cheat Sheet
By Syncfusion®, Inc. · Last updated November 13, 2026
A one-page Node.js reference: core modules, CommonJS and ES module patterns, event loop order, process, fs and path, EventEmitter, streams and buffers, HTTP and networking, child processes and workers, node:test, crypto, CLI flags, package.json fields and npm commands, plus common error codes, error messages with fixes, and a glossary for beginners.
Node.js Cheat Sheet
Every important Node.js API from this course, on one page.
Each table names the lesson that teaches it.
Code uses ES modules (import) unless it says CommonJS.
Keep this page open while you build your own projects.
Core Modules Quick Reference
Module What it does Lesson
node:fs/promisesRead, write and manage files Path and File System
node:pathBuild and split file paths Path and File System
node:eventsEventEmitter, once, onEvents and Utilities
node:utilpromisify, parseArgs, inspect, debuglogEvents and Utilities
node:streamReadable, Writable, Transform, pipeline Buffers, Streams and Compression
node:readlineRead lines from files and stdin Buffers, Streams and Compression
node:zlibgzip, deflate, Brotli Buffers, Streams and Compression
node:httpHTTP servers and clients HTTP and Networking
node:netTCP sockets HTTP and Networking
node:child_processRun other programs Child Processes, Worker Threads and Clustering
node:worker_threadsRun JavaScript on more threads Child Processes, Worker Threads and Clustering
node:test, node:assert/strictTests and checks Testing with the Built-in Test Runner
node:cryptoHashes, HMAC, random values, encryption Cryptography and Security
node:osFacts about the computer Process, OS and CLI Tools
Module Patterns
// ES module (.mjs, or .js with "type": "module")
import fs from "node:fs/promises";
import { average } from "./grades.js"; // full file name needed
import data from "./data.json" with { type: "json" };
export function grade(m) { return m >= 90 ? "A" : "B"; }
export default grade;
const later = await import("./big-module.js"); // dynamic import, top-level await
console.log(import.meta.dirname, import.meta.filename);
// CommonJS (.cjs, or .js without "type": "module")
const fs = require("node:fs");
const { average } = require("./grades"); // .js can be left out
module.exports = { grade }; // never: exports = { ... }
console.log(__dirname, __filename, require.main === module);
Task Code Lesson
Use require inside ESM const require = createRequire(import.meta.url)Modules in Node.js
Run TypeScript node app.ts (types are stripped, not checked)Modules in Node.js
Package entry points "exports": { ".": "./index.js", "./grades": "./grades.js" }Packages and npm
Private short names "imports": { "#config": "./src/config.js" }Packages and npm
Event Loop Order
All sync code from top to bottom.
process.nextTick callbacks.
Promise callbacks and queueMicrotask.
Timers phase: setTimeout, setInterval.
Poll phase: file and network callbacks.
Check phase: setImmediate.
Close callbacks. Then back to step 4. Steps 2 and 3 run again after every callback.
Task Code Lesson
Wait with await await setTimeout(500) from node:timers/promisesEvent Loop and Timers
Let the loop breathe setImmediate(() => nextPiece())Event Loop and Timers
Do not keep the program alive timer.unref()Event Loop and Timers
Thread pool size UV_THREADPOOL_SIZE=8 node app.jsEvent Loop and Timers
process Methods
Task Code Lesson
Command words process.argv.slice(2)Process, OS and CLI Tools
Settings process.env.PORT ?? "3000"Process, OS and CLI Tools
Load a .env file node --env-file=.env app.js or process.loadEnvFile()Process, OS and CLI Tools
Write without new line process.stdout.write("Loading...")Process, OS and CLI Tools
Fail at the end process.exitCode = 1Process, OS and CLI Tools
Stop now process.exit(1)Process, OS and CLI Tools
Clean up on Ctrl + C process.on("SIGINT", cleanup)Process, OS and CLI Tools
Polite stop process.on("SIGTERM", shutdown)Production Readiness
Folder started from process.cwd()Process, OS and CLI Tools
Memory and CPU process.memoryUsage(), process.cpuUsage()Debugging and Profiling
Last safety net process.on("uncaughtException", logAndExit)Error Handling
fs and path Patterns
import { readFile, writeFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
const file = path.join(import.meta.dirname, "data", "marks.csv");
const text = await readFile(file, "utf8"); // text
const json = JSON.parse(await readFile("config.json", "utf8")); // JSON
await mkdir("reports/2026", { recursive: true });
await writeFile("report.json.tmp", JSON.stringify(json)); // safe write:
await rename("report.json.tmp", "report.json"); // temp, then rename
const entries = await readdir("reports", { withFileTypes: true });
const info = await stat("report.json"); // info.size, info.mtime
await rm("old", { recursive: true, force: true });
Task Code Lesson
Glue path parts path.join("a", "b", "c.txt")Path and File System
Absolute path path.resolve("reports")Path and File System
Name, folder, extension path.basename(p), path.dirname(p), path.extname(p)Path and File System
URL to path fileURLToPath(import.meta.url)Path and File System
Write only if new writeFile(p, data, { flag: "wx" })Path and File System
EventEmitter Patterns
import { EventEmitter, once } from "node:events";
class Classroom extends EventEmitter {
join(name) { this.emit("joined", name); }
}
const room = new Classroom();
room.on("joined", (name) => console.log("Hello", name)); // every time
room.once("joined", () => console.log("First student!")); // one time
room.on("error", (err) => console.error(err.message)); // always handle error
const [name] = await once(room, "joined"); // wait for one event
Stream and Buffer Patterns
import { createReadStream, createWriteStream } from "node:fs";
import { createInterface } from "node:readline";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
import { createGzip } from "node:zlib";
for await (const line of createInterface({ input: createReadStream("big.csv") })) { /* one line */ }
await pipeline(createReadStream("log.txt"), createGzip(), createWriteStream("log.txt.gz"));
const upper = new Transform({ transform(chunk, enc, done) { done(null, chunk.toString().toUpperCase()); } });
const buf = Buffer.from("Hi"); // <Buffer 48 69>
buf.toString("base64"); // "SGk="
Buffer.from("SGk=", "base64").toString(); // "Hi"
Task Code Lesson
Backpressure if (!out.write(chunk)) await once(out, "drain")Buffers, Streams and Compression
Stream from a list Readable.from(["a", "b"])Buffers, Streams and Compression
Copy part of a buffer Buffer.from(buf.subarray(0, 4))Buffers, Streams and Compression
HTTP and Networking Patterns
import http from "node:http";
const server = http.createServer(async (req, res) => {
const { pathname, searchParams } = new URL(req.url, "http://localhost");
if (req.method === "POST") {
let body = "";
for await (const chunk of req) body += chunk;
res.writeHead(201, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ saved: JSON.parse(body) }));
}
if (pathname === "/health") return res.writeHead(200).end("ok");
res.writeHead(404).end("Not found");
});
server.listen(3000);
const reply = await fetch("http://localhost:3000/health", { signal: AbortSignal.timeout(2000) });
Task Code Lesson
Any free port server.listen(0) then server.address().portHTTP and Networking
Port busy server.on("error", (e) => e.code === "EADDRINUSE")HTTP and Networking
Serve a file createReadStream(file).pipe(res)HTTP and Networking
Stop gracefully server.close(callback) + closeIdleConnections()Production Readiness
Child Process and Worker Patterns
import { execFile, spawn, fork } from "node:child_process";
import { promisify } from "node:util";
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
const { stdout } = await promisify(execFile)("git", ["log", "--oneline", "-3"]); // no shell
const child = spawn("node", ["job.js"]); child.stdout.on("data", (d) => process.stdout.write(d));
if (isMainThread) {
const w = new Worker(new URL(import.meta.url), { workerData: 1_000_000 });
w.on("message", (result) => console.log(result));
} else {
parentPort.postMessage(heavyMaths(workerData));
}
node:test Patterns
import { test, describe, it, beforeEach, mock } from "node:test";
import assert from "node:assert/strict";
describe("grade", () => {
beforeEach(() => { /* fresh data */ });
it("90 is an A", () => assert.equal(grade(90), "A"));
it("objects", () => assert.deepStrictEqual({ a: [1] }, { a: [1] }));
it("throws", () => assert.throws(() => parse("x"), TypeError));
it("rejects", async () => { await assert.rejects(load(99), /not found/); });
});
test("mocks", (t) => {
const notify = mock.fn();
t.mock.timers.enable({ apis: ["setTimeout"] });
t.mock.timers.tick(1000);
});
Task Command Lesson
Run all tests node --testTesting with the Built-in Test Runner
Watch node --test --watchTesting with the Built-in Test Runner
Coverage node --test --experimental-test-coverageTesting with the Built-in Test Runner
crypto Patterns
import { createHash, createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
createHash("sha256").update("data").digest("hex"); // fingerprint
createHmac("sha256", process.env.SECRET).update(msg).digest("hex"); // signature
randomBytes(32).toString("hex"); // token
randomUUID(); // id
// passwords: salt + scrypt (or pbkdf2) + timingSafeEqual
CLI Flags
Flag What it does
-v, --versionPrint the Node.js version
-e "code", -p "code"Run code, or run it and print the answer
-c, --checkCheck a file for syntax errors
--watchRestart when files change
--env-file=.envLoad settings into process.env
--run <script>Run a package.json script quickly
--testRun tests
--inspect, --inspect-brkAllow a debugger to connect
--enable-source-mapsShow original file lines in errors
--cpu-profWrite a CPU profile
--max-old-space-size=2048Allow a bigger heap (MB)
--permission, --allow-fs-read=dirLimit what the program may touch
--trace-deprecation, --throw-deprecationFind or fail on deprecated APIs
--report-on-fatalerrorWrite a diagnostic report on a fatal crash
package.json Fields
Field Example What it does
name, version"report-card", "1.2.0"Who the package is
type"module".js files are ES modules
main"index.js"Entry file (old style)
exports{ ".": "./index.js" }Public entry points
imports{ "#config": "./src/config.js" }Private short names
bin{ "report-card": "./cli.js" }Command name for a CLI
scripts{ "test": "node --test" }Named commands
engines{ "node": ">=22" }Supported Node.js versions
privatetrueBlock npm publish
files["dist"]What gets published
dependencies / devDependencies{ "dayjs": "^1.11.0" }Packages needed to run / to build
npm Commands
Command What it does
npm init -yMake a package.json
npm install dayjsAdd a dependency
npm install -D typescriptAdd a dev dependency
npm ciClean, exact install from the lockfile
npm run build -- --flagRun a script with arguments
npx tsc --versionRun a tool from node_modules/.bin
npm ls, npm outdated, npm updateCheck and update packages
npm audit, npm audit fixFind and fix known security problems
npm linkInstall your CLI on your own computer
npm pack --dry-run, npm publishPreview and publish a package
Troubleshooting
Common Error Codes
Code Means Fix
ENOENTNo such file or folder Check the path. Build it from import.meta.dirname
EACCES, EPERMNot allowed Use a folder you own. Do not use sudo npm
EEXISTAlready exists Use { recursive: true } or another name
EADDRINUSEPort already in use Stop the other program, or use another port
ECONNREFUSEDNothing is listening there Start the server first, check the port
ECONNRESETThe other side hung up Retry, check the other server's logs
ETIMEDOUTNo answer in time Retry later, raise the timeout
EMFILEToo many open files Close files and handles, open fewer at once
ERR_MODULE_NOT_FOUNDImport path is wrong Add the full file name, such as ./grades.js
ERR_REQUIRE_ESM / ERR_REQUIRE_ASYNC_MODULErequire of an ES module that cannot be requiredUse import, or remove top-level await
ERR_IMPORT_ATTRIBUTE_MISSINGJSON import without the attribute Add with { type: "json" }
ERR_PACKAGE_PATH_NOT_EXPORTEDThat file is not in the package's exports Import a public path
ERR_INVALID_ARG_TYPEWrong type passed to a Node.js API Check the value and its type
ERR_UNSUPPORTED_TYPESCRIPT_SYNTAXenum or similar in node app.tsUse a union type or an object
Common Error Messages and Fixes
Message Likely cause Fix
require is not defined in ES module scoperequire in an ES moduleUse import, or createRequire
__dirname is not defined in ES module scope__dirname in an ES moduleUse import.meta.dirname
Cannot use import statement outside a moduleimport in a CommonJS fileAdd "type": "module" or rename to .mjs
Cannot find module './grades'Wrong path or missing extension Check the path and the extension
'node' is not recognizedNode.js not installed, or an old terminal Install Node.js, open a new terminal
JavaScript heap out of memoryA leak, or too much data at once Stream the data, find the leak, then raise the heap
MaxListenersExceededWarningListeners added again and again Add listeners once, remove them with off
Unhandled 'error' eventAn emitter failed with no listener Add on("error", ...)
write after endWriting to a finished stream Do not write after end()
Cannot set headers after they are sentTwo responses for one request return after sending a response
Glossary
Term Meaning
Node.js A runtime that runs JavaScript outside the browser
Runtime A program that runs code and gives it tools
V8 The engine that runs JavaScript inside Node.js and Chrome
libuv The C library behind the event loop and the thread pool
Event loop Picks the next callback to run, one at a time
Non-blocking Start a slow job and carry on, handle the result later
Callback A function you pass in, to be called later
Promise An object for a result that comes later
Module One file with its own scope and its own exports
Package A folder of code with a package.json, shared with npm
Dependency A package your project needs
SemVer MAJOR.MINOR.PATCH version numbers
Lockfile package-lock.json: the exact installed versions
Environment variable A named setting given to a program from outside
Exit code A number a program returns: 0 means success
Signal A message from the operating system, such as SIGINT
Buffer A box of raw bytes
Stream Data handled a piece at a time
Backpressure Slowing the writer down when the reader is behind
EventEmitter An object that sends named events to listeners
Socket One end of a two-way network connection
Child process Another program started by your program
Worker thread Another JavaScript thread in the same process
Hash A fixed-size fingerprint of data
Graceful shutdown Finish current work and close resources before exiting
Health check A small URL that says whether the app is alive and ready
What to Remember
Use this page to look things up, and the lessons to understand them.
Start new projects with ES modules, fs/promises and node --test.
When an error appears, check its code first, then this page's tables.
Next: Introduction to Express.js in the Express.js course. You will build web servers faster with a framework on top of everything you learned here.