Node.js Cheat Sheet

By Syncfusion®, Inc. · Last updated

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

ModuleWhat it doesLesson
node:fs/promisesRead, write and manage filesPath and File System
node:pathBuild and split file pathsPath and File System
node:eventsEventEmitter, once, onEvents and Utilities
node:utilpromisify, parseArgs, inspect, debuglogEvents and Utilities
node:streamReadable, Writable, Transform, pipelineBuffers, Streams and Compression
node:readlineRead lines from files and stdinBuffers, Streams and Compression
node:zlibgzip, deflate, BrotliBuffers, Streams and Compression
node:httpHTTP servers and clientsHTTP and Networking
node:netTCP socketsHTTP and Networking
node:child_processRun other programsChild Processes, Worker Threads and Clustering
node:worker_threadsRun JavaScript on more threadsChild Processes, Worker Threads and Clustering
node:test, node:assert/strictTests and checksTesting with the Built-in Test Runner
node:cryptoHashes, HMAC, random values, encryptionCryptography and Security
node:osFacts about the computerProcess, 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);
TaskCodeLesson
Use require inside ESMconst require = createRequire(import.meta.url)Modules in Node.js
Run TypeScriptnode 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

  1. All sync code from top to bottom.
  2. process.nextTick callbacks.
  3. Promise callbacks and queueMicrotask.
  4. Timers phase: setTimeout, setInterval.
  5. Poll phase: file and network callbacks.
  6. Check phase: setImmediate.
  7. Close callbacks. Then back to step 4. Steps 2 and 3 run again after every callback.
TaskCodeLesson
Wait with awaitawait setTimeout(500) from node:timers/promisesEvent Loop and Timers
Let the loop breathesetImmediate(() => nextPiece())Event Loop and Timers
Do not keep the program alivetimer.unref()Event Loop and Timers
Thread pool sizeUV_THREADPOOL_SIZE=8 node app.jsEvent Loop and Timers

process Methods

TaskCodeLesson
Command wordsprocess.argv.slice(2)Process, OS and CLI Tools
Settingsprocess.env.PORT ?? "3000"Process, OS and CLI Tools
Load a .env filenode --env-file=.env app.js or process.loadEnvFile()Process, OS and CLI Tools
Write without new lineprocess.stdout.write("Loading...")Process, OS and CLI Tools
Fail at the endprocess.exitCode = 1Process, OS and CLI Tools
Stop nowprocess.exit(1)Process, OS and CLI Tools
Clean up on Ctrl + Cprocess.on("SIGINT", cleanup)Process, OS and CLI Tools
Polite stopprocess.on("SIGTERM", shutdown)Production Readiness
Folder started fromprocess.cwd()Process, OS and CLI Tools
Memory and CPUprocess.memoryUsage(), process.cpuUsage()Debugging and Profiling
Last safety netprocess.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 });
TaskCodeLesson
Glue path partspath.join("a", "b", "c.txt")Path and File System
Absolute pathpath.resolve("reports")Path and File System
Name, folder, extensionpath.basename(p), path.dirname(p), path.extname(p)Path and File System
URL to pathfileURLToPath(import.meta.url)Path and File System
Write only if newwriteFile(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"
TaskCodeLesson
Backpressureif (!out.write(chunk)) await once(out, "drain")Buffers, Streams and Compression
Stream from a listReadable.from(["a", "b"])Buffers, Streams and Compression
Copy part of a bufferBuffer.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) });
TaskCodeLesson
Any free portserver.listen(0) then server.address().portHTTP and Networking
Port busyserver.on("error", (e) => e.code === "EADDRINUSE")HTTP and Networking
Serve a filecreateReadStream(file).pipe(res)HTTP and Networking
Stop gracefullyserver.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);
});
TaskCommandLesson
Run all testsnode --testTesting with the Built-in Test Runner
Watchnode --test --watchTesting with the Built-in Test Runner
Coveragenode --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

FlagWhat 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

FieldExampleWhat 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

CommandWhat 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

CodeMeansFix
ENOENTNo such file or folderCheck the path. Build it from import.meta.dirname
EACCES, EPERMNot allowedUse a folder you own. Do not use sudo npm
EEXISTAlready existsUse { recursive: true } or another name
EADDRINUSEPort already in useStop the other program, or use another port
ECONNREFUSEDNothing is listening thereStart the server first, check the port
ECONNRESETThe other side hung upRetry, check the other server's logs
ETIMEDOUTNo answer in timeRetry later, raise the timeout
EMFILEToo many open filesClose files and handles, open fewer at once
ERR_MODULE_NOT_FOUNDImport path is wrongAdd 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 attributeAdd with { type: "json" }
ERR_PACKAGE_PATH_NOT_EXPORTEDThat file is not in the package's exportsImport a public path
ERR_INVALID_ARG_TYPEWrong type passed to a Node.js APICheck 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

MessageLikely causeFix
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 extensionCheck the path and the extension
'node' is not recognizedNode.js not installed, or an old terminalInstall Node.js, open a new terminal
JavaScript heap out of memoryA leak, or too much data at onceStream the data, find the leak, then raise the heap
MaxListenersExceededWarningListeners added again and againAdd listeners once, remove them with off
Unhandled 'error' eventAn emitter failed with no listenerAdd on("error", ...)
write after endWriting to a finished streamDo not write after end()
Cannot set headers after they are sentTwo responses for one requestreturn after sending a response

Glossary

TermMeaning
Node.jsA runtime that runs JavaScript outside the browser
RuntimeA program that runs code and gives it tools
V8The engine that runs JavaScript inside Node.js and Chrome
libuvThe C library behind the event loop and the thread pool
Event loopPicks the next callback to run, one at a time
Non-blockingStart a slow job and carry on, handle the result later
CallbackA function you pass in, to be called later
PromiseAn object for a result that comes later
ModuleOne file with its own scope and its own exports
PackageA folder of code with a package.json, shared with npm
DependencyA package your project needs
SemVerMAJOR.MINOR.PATCH version numbers
Lockfilepackage-lock.json: the exact installed versions
Environment variableA named setting given to a program from outside
Exit codeA number a program returns: 0 means success
SignalA message from the operating system, such as SIGINT
BufferA box of raw bytes
StreamData handled a piece at a time
BackpressureSlowing the writer down when the reader is behind
EventEmitterAn object that sends named events to listeners
SocketOne end of a two-way network connection
Child processAnother program started by your program
Worker threadAnother JavaScript thread in the same process
HashA fixed-size fingerprint of data
Graceful shutdownFinish current work and close resources before exiting
Health checkA 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.