Node.js Cheatsheet
Interview Quick Reference
Use this Node.js reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Reading Input in Coding Challenges
// Read all of stdin, then solve (the pattern judges/online compilers expect) process.stdin.resume(); let input = ""; process.stdin.on("data", (d) => (input += d)); process.stdin.on("end", () => { const lines = input.split("\n"); const [n, k] = lines[0].split(" ").map(Number); const nums = lines[1].split(" ").map(Number); console.log(solve(n, k, nums)); }); // Modern one-liner equivalents import { text } from "node:stream/consumers"; const input2 = await text(process.stdin); import fs from "node:fs"; const input3 = fs.readFileSync(0, "utf8"); // fd 0 = stdin
Implement-It-Yourself Classics
// promisify — "convert this callback API to promises" function promisify(fn) { return (...args) => new Promise((resolve, reject) => { fn(...args, (err, result) => (err ? reject(err) : resolve(result))); }); } // Minimal EventEmitter class Emitter { #listeners = new Map(); on(event, fn) { if (!this.#listeners.has(event)) this.#listeners.set(event, new Set()); this.#listeners.get(event).add(fn); return this; } off(event, fn) { this.#listeners.get(event)?.delete(fn); return this; } emit(event, ...args) { for (const fn of this.#listeners.get(event) ?? []) fn(...args); } } // sleep const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // Promise.all from scratch function promiseAll(promises) { return new Promise((resolve, reject) => { const results = new Array(promises.length); let remaining = promises.length; if (remaining === 0) return resolve(results); promises.forEach((p, i) => { Promise.resolve(p).then((val) => { results[i] = val; if (--remaining === 0) resolve(results); }, reject); }); }); } // LRU cache with Map (insertion order = recency) class LRU { constructor(cap) { this.cap = cap; this.map = new Map(); } get(k) { if (!this.map.has(k)) return undefined; const v = this.map.get(k); this.map.delete(k); this.map.set(k, v); // bump to most-recent return v; } set(k, v) { this.map.delete(k); this.map.set(k, v); if (this.map.size > this.cap) this.map.delete(this.map.keys().next().value); } }
Predict-the-Output Drills
// Classic ordering question — say the answer before running it console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); process.nextTick(() => console.log("D")); console.log("E"); // A, E, D, C, B (sync → nextTick → microtasks → timers) — CommonJS // At ESM top level it's A, E, C, D, B: module evaluation runs in a microtask, delaying nextTick // Closure-in-a-loop for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3 for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2 // await pauses only the current async function async function f() { console.log(1); await null; // everything after this line is a microtask console.log(3); } f(); console.log(2); // 1 2 3
Rapid-Fire Answers
| Question | Key points |
|---|---|
| Is Node single-threaded? | One JS thread + libuv thread pool (fs, dns, crypto) + optional worker_threads |
process.nextTick vs setImmediate? | nextTick drains before microtasks, same phase; setImmediate runs in the check phase after I/O |
| How does Node handle 10k connections? | Non-blocking I/O multiplexed on one event loop — no thread per connection |
| ESM vs CommonJS? | import is static/async/tree-shakable; require is dynamic/sync; Node 22.12+ allows require(esm) |
| What is backpressure? | Producer outpacing consumer; write() returns false → pause until drain (or just use pipeline) |
Buffer vs string? | Buffer is raw bytes outside the V8 string heap; needed for binary data and encodings |
| CPU-bound task blocks the server — fix? | Move it to worker_threads, chunk it with setImmediate, or offload to a queue |
cluster vs worker_threads? | Processes sharing a port vs threads sharing memory; scaling HTTP vs parallel compute |
| Unhandled rejection behavior? | Crashes the process by default (Node 15+); add a process.on("unhandledRejection") last resort |
Why is readFileSync bad in a server? | Blocks the event loop — every concurrent request stalls until it finishes |