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.
node -v
npm -v
npx --yes cowsay "hi"
node app.js
node --watch app.js
node --env-file=.env app.js
node --inspect app.js
const fs = require("fs");
module.exports = { add(a, b) { return a + b; } };
exports.PI = 3.14;
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");
{
"name": "my-app",
"type": "module",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"test": "node --test"
},
"engines": { "node": ">=20" }
}
npm init -y
npm i express
npm i -D nodemon
npm uninstall lodash
npm update
npx eslint . 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 });
const raw = fs.readFileSync("a.txt", "utf8");
const rs = fs.createReadStream("big.bin");
const ws = fs.createWriteStream("copy.bin");
rs.pipe(ws); 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");
path.basename("/tmp/a.png", ".png");
path.parse("/tmp/a.png"); 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");
});
const res = await fetch("https://api.example.com");
const json = await res.json(); 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);
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")
);
process.env.NODE_ENV;
process.argv;
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); import { spawn, execFile } from "node:child_process";
const child = spawn("node", ["-v"], { stdio: "inherit" });
child.on("exit", (code) => {});
execFile("node", ["-p", "1+1"], (err, out) => {
if (err) throw err;
console.log(out);
}); 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); ⏳Async Patterns & Testing
const ac = new AbortController();
const data = await fetch("/api", { signal: ac.signal });
ac.abort();
const [a, b] = await Promise.all([
readFile("a.txt", "utf8"),
readFile("b.txt", "utf8")
]);
import { test } from "node:test";
import assert from "node:assert/strict";
test("adds", () => {
assert.equal(1 + 1, 2);
}); ⚠️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 |