Skip to main content
Quick Reference

Node.js Cheatsheet

Node.js quick reference — CLI, modules (CJS/ESM), npm, fs, path, HTTP, events, streams, process, child processes, Express basics, async patterns, and colorized snippets.

CLI & Runtime

# Check runtime
node -v
npm -v
npx --yes cowsay "hi"

# Run scripts
node app.js
node --watch app.js          # Node 18+
node --env-file=.env app.js   # Node 20+
node --inspect app.js
Command / flagNotes
node file.jsRun a script
node --watchRestart on file changes (18+)
node --env-file=.envLoad env file (20.6+)
node --inspectChrome DevTools debugging
node --testBuilt-in test runner
npx pkgRun a package binary without global install

Modules (CJS & ESM)

// CommonJS
const fs = require("fs");
module.exports = { add(a, b) { return a + b; } };
exports.PI = 3.14;

// ESM (package.json: "type": "module"  OR  .mjs)
import fs from "node:fs/promises";
import { readFile } from "node:fs/promises";
export const PI = 3.14;
export default function main() { }

const mod = await import("./lazy.js");
APINotes
require / module.exportsCommonJS — default in .js without "type":"module"
import / exportESM — use "type":"module" or .mjs
node: prefixExplicit core modules e.g. node:fs
import.meta.urlCurrent module URL (ESM __filename substitute)
await import()Dynamic import (works in CJS too)

npm & package.json

# package.json essentials
{
  "name": "my-app",
  "type": "module",
  "scripts": {
    "start": "node src/index.js",
    "dev": "node --watch src/index.js",
    "test": "node --test"
  },
  "engines": { "node": ">=20" }
}

# Commands
npm init -y
npm i express
npm i -D nodemon
npm uninstall lodash
npm update
npx eslint .
Field / commandNotes
dependencies / devDependenciesRuntime vs build/test tools
scriptsnpm run <name>; lifecycle: start, test
enginesDeclare supported Node version
npm i / npm i -DInstall prod / dev dependency
package-lock.jsonLock exact tree — commit it
Semver^1.2.3 minor, ~1.2.3 patch, 1.2.3 exact

File System

import { readFile, writeFile, mkdir } from "node:fs/promises";
import fs from "node:fs";

const data = await readFile("notes.txt", "utf8");
await writeFile("out.txt", data, "utf8");
await mkdir("logs", { recursive: true });

// Sync (blocks event loop — use sparingly)
const raw = fs.readFileSync("a.txt", "utf8");

// Streams for large files
const rs = fs.createReadStream("big.bin");
const ws = fs.createWriteStream("copy.bin");
rs.pipe(ws);
APINotes
fs/promisesPromise-based API (prefer)
readFile / writeFile / appendFileWhole-file IO
mkdir + recursiveCreate nested dirs
readdir / stat / rmList / metadata / delete
createReadStream / WriteStreamLarge files without loading all RAM
*SyncBlocks event loop — scripts/CLI only

Path & URL

import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

path.join(__dirname, "data", "a.json");
path.resolve(".", "src");
path.extname("a.png");     // ".png"
path.basename("/tmp/a.png", ".png");
path.parse("/tmp/a.png");
APINotes
path.joinJoin segments with correct separators
path.resolveAbsolute path from CWD
path.dirname / basename / extnameParse parts
fileURLToPathConvert import.meta.url → path
URL / URLSearchParamsWHATWG URL APIs (global)

HTTP / HTTPS

import http from "node:http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello Node");
});

server.listen(3000, () => {
  console.log("http://localhost:3000");
});

// HTTPS: https.createServer({ key, cert }, handler)
// fetch() is available globally in modern Node
const res = await fetch("https://api.example.com");
const json = await res.json();
APINotes
http.createServerLow-level server
req / resIncomingMessage / ServerResponse
res.writeHead + endStatus, headers, body
fetchGlobal client in modern Node
httpsTLS server/client; need certs for server

Events

import { EventEmitter } from "node:events";

const bus = new EventEmitter();
bus.on("msg", (text) => console.log(text));
bus.once("ready", () => {});
bus.emit("msg", "hi");
bus.off("msg", handler);

// Prefer async iterators / AbortSignal for cancellation in new code
MethodNotes
on / addListenerSubscribe
onceFire once then remove
emitPublish event + args
off / removeListenerUnsubscribe
setMaxListenersRaise warning threshold

Streams

import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import fs from "node:fs";
import zlib from "node:zlib";

await pipeline(
  fs.createReadStream("a.txt"),
  zlib.createGzip(),
  fs.createWriteStream("a.txt.gz")
);

// Modes: readable / writable / duplex / transform
// Always handle error events or use pipeline()
Type / APINotes
Readable / WritableSource / sink
Duplex / TransformBoth directions / map chunks
pipeConnect streams (error handling easy to miss)
pipelineSafer chaining + cleanup (prefer)
zlib / cryptoCommon transform streams

Process, Env & OS

process.env.NODE_ENV;
process.argv;                 // CLI args
process.cwd();
process.chdir("/tmp");
process.exit(0);
process.on("uncaughtException", handler);
process.on("unhandledRejection", handler);

import os from "node:os";
os.platform();  os.cpus();  os.homedir();

import { setTimeout } from "node:timers/promises";
await setTimeout(1000);
APINotes
process.envEnvironment variables (strings)
process.argv[node, script, ...args]
process.cwd / chdirWorking directory
process.exit(code)Prefer graceful shutdown when possible
osPlatform, CPUs, memory, homedir
timers/promisesawait setTimeout(ms)

Child Processes

import { spawn, execFile } from "node:child_process";

const child = spawn("node", ["-v"], { stdio: "inherit" });
child.on("exit", (code) => {});

// Prefer execFile over exec (shell injection)
execFile("node", ["-p", "1+1"], (err, out) => {
  if (err) throw err;
  console.log(out);
});
APINotes
spawnStream stdio; long-running processes
execFileBuffered output; safer than exec
execRuns in shell — injection risk with user input
forkSpawn another Node process with IPC
stdiopipe | inherit | ignore

Express (common stack)

import express from "express";

const app = express();
app.use(express.json());

app.get("/health", (req, res) => {
  res.json({ ok: true });
});

app.post("/users", async (req, res, next) => {
  try {
    const user = req.body;
    res.status(201).json(user);
  } catch (e) { next(e); }
});

app.listen(3000);
APINotes
app.get/post/put/deleteRoute handlers
app.useMiddleware (order matters)
express.json()Parse JSON body
req.params / query / bodyRequest data
res.status().json()JSON responses
next(err)Forward to error middleware

Async Patterns & Testing

// Promises + AbortSignal
const ac = new AbortController();
const data = await fetch("/api", { signal: ac.signal });
ac.abort();

// Parallel
const [a, b] = await Promise.all([
  readFile("a.txt", "utf8"),
  readFile("b.txt", "utf8")
]);

// node:test runner
import { test } from "node:test";
import assert from "node:assert/strict";
test("adds", () => {
  assert.equal(1 + 1, 2);
});
PatternNotes
async/awaitPrefer over raw callbacks
AbortControllerCancel fetch / some Node APIs
Promise.allParallel independent work
node:test + assertBuilt-in tests — no Jest required
Error-first callbacksLegacy style: (err, data) =>

Gotchas & Interview Tips

  • Node is single-threaded for JS — heavy CPU work blocks the event loop; use workers or offload.
  • Never use sync fs APIs on a request path.
  • Prefer node: imports and ESM for new projects; know CJS interop for legacy packages.
  • Always handle promise rejections and stream error events (or use pipeline).
  • process.env values are strings — coerce numbers/booleans yourself.
  • Avoid exec with user input (shell injection); use execFile/spawn with arg arrays.
  • Commit package-lock.json; pin Node via engines / .nvmrc.
  • Middleware order in Express matters; put error handlers last ((err, req, res, next)).

Next: Node.js tutorial · Cheatsheet hub · JavaScript