PrepStack › Backend › Node.js

Node.js interview cheat sheet

Event loop, modules, streams, processes and production Node

Node.js interviews check whether you really understand one thread plus an event loop: why I/O does not block, what does block, and in which order nextTick, promises, timers and setImmediate run. Then they move to core APIs (modules, EventEmitter, streams, Buffer, fs, http), error handling, and running Node in production: workers, cluster, PM2, memory leaks and security. Read the 15-minute revision, run the output puzzles in your head, then use Quiz mode.

15-minute revision

  1. Node = V8 (runs JavaScript) + libuv (event loop, async I/O, thread pool) + C++ bindings + the JS standard library (fs, http, stream...).
  2. Your JavaScript runs on one main thread. I/O is handed to the OS (sockets) or the libuv thread pool (files, DNS lookup, some crypto, zlib), and callbacks come back through the event loop.
  3. Event loop phases: timers → pending callbacks → poll → check → close callbacks. setTimeout runs in timers, I/O callbacks in poll, setImmediate in check.
  4. Priority after each callback: process.nextTick queue first, then promise microtasks, then the next macrotask. Recursive nextTick can starve I/O.
  5. Inside an I/O callback, setImmediate always runs before setTimeout(fn, 0). In the main module their order is not guaranteed.
  6. Thread pool default size is 4; change it with the UV_THREADPOOL_SIZE env var before startup. Network I/O does not use the pool.
  7. Blocking the loop: sync fs/crypto, huge JSON.parse, catastrophic regex, long loops. Fix with async APIs, chunking with setImmediate, or worker_threads.
  8. CommonJS: require is sync, dynamic, cached, wraps each file in a function (exports, require, module, __filename, __dirname). ESM: import is static, async, live bindings, top-level await.
  9. Module type: .mjs = ESM, .cjs = CJS, .js follows "type" in the nearest package.json. Since 22.12 require() can load sync ESM.
  10. EventEmitter listeners run synchronously in registration order. An 'error' event with no listener throws.
  11. 4 stream types: Readable, Writable, Duplex, Transform. write() returning false = backpressure, wait for 'drain'. Prefer stream.pipeline over .pipe (it forwards errors and cleans up).
  12. Buffer = fixed-size raw bytes (a Uint8Array subclass). Buffer.alloc is zero-filled; allocUnsafe is faster but may hold old memory.
  13. Errors: error-first callbacks, try/catch around await, 'error' events. uncaughtException / unhandledRejection are last-resort loggers: log, then exit and let a supervisor restart.
  14. CPU work → worker_threads. Another program → child_process. Use all CPU cores for a server → cluster / PM2 / several containers behind a load balancer.
  15. ^1.2.3 allows minor + patch updates, ~1.2.3 allows patch only. Commit the lockfile and use npm ci in CI.
  16. Modern Node (22/24/26 LTS): built-in node:test, global fetch, --watch, --env-file, node --run, require(esm), and TypeScript type stripping on by default (22.18+, 23.6+).

Foundations

What Node.js is: V8, libuv & non-blocking I/O

Node is a JavaScript runtime: V8 runs your code on one thread, and libuv does I/O in the background and reports back through the event loop.

  • V8 compiles and runs JavaScript (JIT, garbage collector). It knows nothing about files or sockets.
  • libuv is a C library that gives Node the event loop, non-blocking sockets (epoll / kqueue / IOCP) and a small thread pool for work the OS cannot do asynchronously.
  • Single-threaded means your JavaScript runs on one main thread. Node itself uses more threads (thread pool, V8 GC and compiler threads).
  • Non-blocking I/O: you start an operation, pass a callback or get a promise, and the thread moves on. When the result is ready, the callback is queued and run by the event loop.
  • This model is great for I/O-bound work (APIs, proxies, chat, streaming) and poor for CPU-bound work unless you move it to worker threads.
  • Node is not a framework or a language. Express, Fastify and NestJS are frameworks that run on Node.

Interview questions

  • What is Node.js?
  • If Node is single-threaded, how does it handle many requests at once?
  • When should you NOT use Node.js?
  • What is the role of libuv?

CommonJS vs ES modules

CommonJS (require) is synchronous and dynamic. ES modules (import) are static, load asynchronously and allow top-level await.

  • CommonJS: module.exports / require(). Loaded synchronously at runtime, so you can require inside an if. Default for .js files when package.json has no "type" field.
  • ESM: export / import. Imports are parsed before running, which enables static analysis and tree-shaking. Exports are live bindings, not copies.
  • How Node decides: .mjs is ESM, .cjs is CJS, .js follows "type": "module" or "commonjs" in the nearest package.json.
  • ESM has no __dirname, __filename, require or module. Use import.meta.dirname / import.meta.filename (Node 20.11+) or import.meta.url.
  • ESM can import CJS (you get module.exports as the default export). CJS can load ESM with await import() and, since 22.12 / 20.19, with require() if the ESM graph has no top-level await.
  • Relative ESM imports need the file extension: import x from './util.js', not './util'.

Interview questions

  • Difference between CommonJS and ES modules?
  • How does Node decide whether a file is ESM or CommonJS?
  • Can you require() an ES module?
  • What is the difference between exports and module.exports?

require(): resolution, module wrapper & cache

require resolves a path, wraps the file in a function, runs it once, and caches module.exports for every later call.

  • Resolution order: built-in module (fs, node:fs) → relative/absolute path (tries .js, .json, .node, then a folder's package.json main or index.js) → walk up node_modules folders.
  • Module wrapper: before running, Node wraps the file in (function (exports, require, module, __filename, __dirname) { ... }). That is why top-level variables are private and these 5 names exist.
  • Caching: after the first load, the module is stored in require.cache keyed by its resolved filename. Later require calls return the same module.exports object, so modules act like singletons.
  • Deleting require.cache[require.resolve(p)] forces a reload (used by hot-reload tools and tests).
  • Circular dependencies: if A requires B and B requires A, B gets A's partially filled exports. Avoid cycles or move the require inside the function that needs it.

Interview questions

  • What is the module wrapper function?
  • What happens when you require the same module twice?
  • How does Node handle circular require calls?
  • How does require('express') find the package?

npm, package.json, semver & lockfiles

package.json declares what you need, semver ranges say which versions are acceptable, and the lockfile pins exactly what was installed.

  • package.json holds name, version, scripts, dependencies, devDependencies, peerDependencies, engines, type, main/exports.
  • Semver MAJOR.MINOR.PATCH: major = breaking change, minor = new backward-compatible feature, patch = bug fix.
  • package-lock.json records the exact version and integrity hash of every package in the tree. Commit it for apps so every install is identical.
  • npm install may update the lockfile within ranges. npm ci deletes node_modules, installs exactly from the lockfile and fails if it disagrees with package.json — use it in CI and Docker.
  • npx runs a package binary without installing it globally. npm run <script> runs a script with node_modules/.bin on the PATH.
  • Other tools: pnpm (content-addressed store, strict node_modules), Yarn, and Corepack to pin the package manager version.

Interview questions

  • Difference between dependencies and devDependencies?
  • What does ^ vs ~ mean in a version?
  • Why commit package-lock.json, and what is npm ci?
  • What is a peer dependency?

Event loop & async

The event loop and its phases

libuv runs a loop of phases; each phase has a FIFO queue of callbacks, and Node drains nextTick and promise queues between every callback.

  • timers: callbacks from setTimeout / setInterval whose time has passed. The delay is a minimum, not a guarantee.
  • pending callbacks: some system callbacks deferred from the previous iteration (for example certain TCP errors).
  • poll: wait for new I/O events and run their callbacks (file reads, sockets, incoming requests). The loop blocks here when there is nothing else to do.
  • check: setImmediate callbacks, run right after poll.
  • close callbacks: 'close' events such as socket.on('close').
  • After each callback Node empties the process.nextTick queue, then the promise microtask queue. The process exits when no timers, handles or requests are left.
  • Detail for seniors: since libuv 1.45 (Node 20), timers are processed after poll in each iteration (and once before the loop starts). The classic diagram still predicts the outputs interviewers ask about.

Interview questions

  • Explain the Node.js event loop.
  • What happens in the poll phase?
  • Why does setImmediate run before setTimeout(0) inside an fs callback?
  • How is Node's event loop different from the browser's?

nextTick vs microtasks vs setImmediate vs setTimeout

Sync code → process.nextTick → promise microtasks → timers / I/O / immediates, with both small queues drained after every callback.

  • process.nextTick runs as soon as the current JavaScript operation finishes, before any promise callback. It is Node-only.
  • Microtasks (.then, await continuations, queueMicrotask) run after the nextTick queue is empty.
  • Node drains the queues in a loop: all nextTicks, then all microtasks; if microtasks added new nextTicks, those run after the microtask queue empties.
  • setImmediate = “run in the check phase of this loop iteration”. setTimeout(fn, 0) = “run in the timers phase once at least 1 ms has passed”.
  • Docs advice: prefer setImmediate or queueMicrotask over nextTick; recursive nextTick starves the event loop because I/O never gets a turn.

Interview questions

  • Difference between process.nextTick and setImmediate?
  • Which runs first: process.nextTick or Promise.then?
  • What is event loop starvation?
  • Predict: setTimeout(a, 0); setImmediate(b); at the top of a script.

libuv thread pool

A fixed pool (default 4 threads) runs blocking system work such as file I/O, dns.lookup, async crypto and zlib; network sockets do not use it.

  • Uses the pool: all async fs APIs (except watchers), dns.lookup() (so most HTTP client hostname lookups), async crypto (pbkdf2, scrypt, randomBytes, randomFill, generateKeyPair) and async zlib.
  • Does not use the pool: TCP/UDP sockets, HTTP servers, pipes, timers. These use OS async I/O.
  • Default size is 4. Set UV_THREADPOOL_SIZE (max 1024) in the environment before Node starts; setting process.env inside the app is not reliable because the pool may already exist.
  • With 4 threads, the 5th concurrent pbkdf2 call waits in the queue. A slow disk or many dns.lookup calls can delay unrelated fs work.
  • dns.resolve*() uses c-ares over the network and does not use the pool; dns.lookup() calls the OS resolver (getaddrinfo) on the pool.

Interview questions

  • What is the libuv thread pool and what uses it?
  • How do you change the thread pool size, and when should you?
  • Does http.createServer use the thread pool for each request?

Blocking the event loop

Any long synchronous work freezes every request; keep each callback short and move CPU work off the main thread.

  • Common blockers: sync APIs (readFileSync, pbkdf2Sync) in request handlers, JSON.parse/stringify of huge payloads, catastrophic regex (ReDoS), big sorts or loops, and sync compression.
  • Symptoms: latency spikes for all users, timers firing late, health checks timing out while CPU sits at 100% on one core.
  • Fixes: use async APIs; partition work into chunks and yield with setImmediate; offload to worker_threads or another service; stream large data instead of loading it all.
  • Measure with perf_hooks.monitorEventLoopDelay(), --cpu-prof, or Clinic.js. A loop delay above tens of ms under load is a warning sign.
  • Sync APIs are fine at startup (loading config) and in CLI scripts, where nothing else is waiting.

Interview questions

  • What does “blocking the event loop” mean and how do you detect it?
  • A route that hashes passwords with bcrypt makes the whole API slow. Why and what do you do?
  • How do you run a CPU-heavy task without blocking requests?

Core APIs

EventEmitter

EventEmitter is Node's built-in pub/sub: on registers listeners and emit calls them synchronously in order.

  • Most core objects are emitters: servers, sockets, streams, process, child processes.
  • on/addListener, once, off/removeListener, prependListener, listenerCount, eventNames.
  • emit calls listeners synchronously and returns true if there were any. Use setImmediate or queueMicrotask inside a listener for async behavior.
  • 'error' is special: emitting it with no listener throws the error and can crash the process.
  • More than 10 listeners for one event prints a MaxListenersExceededWarning — usually a sign of a listener leak. Adjust with setMaxListeners only if it is intentional.
  • events.once(emitter, 'name') returns a promise; events.on(emitter, 'name') returns an async iterator.

Interview questions

  • What is EventEmitter and where is it used?
  • Are EventEmitter listeners synchronous or asynchronous?
  • What happens if an 'error' event is emitted with no listener?
  • What does “MaxListenersExceededWarning: possible EventEmitter memory leak” mean?

Buffer & binary data

A Buffer is a fixed-length chunk of raw bytes outside the V8 heap, used for files, sockets, crypto and encodings.

  • Buffer is a subclass of Uint8Array, so typed-array methods work. Its memory lives outside the JS heap (counted in external / arrayBuffers).
  • Create: Buffer.from(string, encoding), Buffer.from(array), Buffer.alloc(n) (zero-filled), Buffer.allocUnsafe(n) (fast, may contain old data).
  • Encodings: utf8 (default), hex, base64, base64url, latin1, ascii, utf16le.
  • buf.length is bytes, not characters. 'é' is 2 bytes in UTF-8; use Buffer.byteLength(str).
  • subarray/slice return a view sharing memory; changes show up in the original. Copy with Buffer.from(buf).

Interview questions

  • What is a Buffer and why does Node need it?
  • Difference between Buffer.alloc and Buffer.allocUnsafe?
  • Why can buf.length differ from str.length?

fs: sync vs callback vs promises

Three flavours of the same API: fs.xSync blocks, fs.x(cb) uses error-first callbacks, fs/promises returns promises for async/await.

  • Sync (readFileSync): simplest, blocks the event loop. OK for startup and CLIs, wrong in request handlers.
  • Callback (readFile(path, cb)): non-blocking, error-first. Oldest style, easy to nest into callback hell.
  • Promises (require('fs/promises') or fs.promises): non-blocking, works with await and Promise.all. Default choice in modern code.
  • readFile loads the whole file into memory. For large files use streams (createReadStream) or FileHandle.readLines().
  • fs.existsSync is fine, but checking before opening is a race condition. Just open the file and handle ENOENT.
  • fs.watch uses OS notifications and is not consistent across platforms; tools like chokidar smooth it out.

Interview questions

  • Difference between fs.readFile and fs.readFileSync?
  • Difference between fs.readFile and fs.createReadStream?
  • What is callback hell and how do you avoid it?

Streams, backpressure & pipeline

Streams process data piece by piece; backpressure stops a fast producer from flooding a slow consumer, and pipeline wires it all up safely.

  • Readable (source: fs.createReadStream, req), Writable (sink: res, file), Duplex (both, independent: TCP socket), Transform (duplex where output is computed from input: gzip, cipher).
  • Readables run in paused or flowing mode. Adding a 'data' listener or calling pipe switches to flowing; for await...of is the modern way to consume.
  • Backpressure: writable.write() returns false once the internal buffer reaches highWaterMark. Stop writing and wait for 'drain'.
  • highWaterMark default: 64 KiB for byte streams since Node 22 (16 KiB before), 16 objects in object mode.
  • stream.pipeline(a, b, c, cb) or require('stream/promises').pipeline handles backpressure, forwards errors, and destroys all streams on failure. Plain .pipe() does not forward errors.
  • Readable.from(iterable) builds a stream from arrays or async generators. Web Streams (ReadableStream) also exist for fetch compatibility.

Interview questions

  • What are streams and why use them?
  • Name the 4 types of streams.
  • What is backpressure and how does Node handle it?
  • Why prefer stream.pipeline over .pipe()?

The http module: building a server

http.createServer(handler) calls your handler with a Readable request and a Writable response for every incoming request.

  • req is an IncomingMessage (Readable): req.method, req.url, req.headers. The body arrives as a stream of chunks.
  • res is a ServerResponse (Writable): res.statusCode, res.setHeader, res.writeHead, res.write, res.end. Forgetting res.end() leaves the client hanging.
  • Parse URLs with the WHATWG URL class; url.parse() is deprecated.
  • Keep-alive connections are reused by default; tune server.keepAliveTimeout and headersTimeout behind load balancers.
  • Frameworks (Express, Fastify, Koa, NestJS) add routing, body parsing and middleware on top of this same API.
  • Global fetch (built on Undici) is the built-in HTTP client; it is stable since Node 21.

Interview questions

  • How do you create an HTTP server without Express?
  • How do you read a POST body in plain Node?
  • What does Express add on top of the http module?

Errors & the process

Error handling: callbacks, promises & process events

Handle errors where they happen (error-first callbacks, try/catch around await, 'error' events); treat process-level handlers as a last resort before exiting.

  • Error-first callbacks: cb(err, result). Always check err first and return after handling it.
  • Promises: .catch() or try/catch around await. A try/catch does not catch errors thrown later inside a callback or timer.
  • Emitters and streams report errors through the 'error' event; without a listener, the process crashes.
  • unhandledRejection: since Node 15 the default mode is throw, so an unhandled rejection crashes the process.
  • uncaughtException: last-chance handler. The app may be in an unknown state; log, flush, close the server, and exit (process.exit(1)). Let PM2, systemd or Kubernetes restart it.
  • Operational errors (network down, bad input, ENOENT) are expected; handle them. Programmer errors (TypeError, undefined property) are bugs; crash and fix.

Interview questions

  • What is the error-first callback pattern?
  • Difference between uncaughtException and unhandledRejection?
  • Should you keep the process running after uncaughtException?
  • Why doesn't try/catch catch an error thrown in a setTimeout callback?

process, environment variables & signals

process is the global handle to the running Node process: argv, env, exit codes, stdio, memory, and OS signals for graceful shutdown.

  • process.argv (array of CLI args), process.env (env vars; always strings), process.cwd(), process.pid, process.platform, process.version.
  • process.exitCode = 1 sets the exit code and lets pending work finish. process.exit(1) stops immediately, possibly cutting off async logging.
  • --env-file=.env loads a dotenv file without the dotenv package (Node 20.6+). process.loadEnvFile() does it from code (21.7+ / 20.12+).
  • Signals: SIGTERM (polite stop: Docker, Kubernetes, PM2), SIGINT (Ctrl+C), SIGKILL (cannot be caught). Adding a listener replaces Node's default exit behaviour.
  • Graceful shutdown: on SIGTERM stop accepting connections (server.close()), finish in-flight requests, close DB pools, then exit, with a hard timeout as a safety net.
  • Events: 'exit' (sync work only), 'beforeExit' (loop is empty, can schedule more), 'warning'.

Interview questions

  • How do you read command-line arguments and environment variables?
  • How do you implement graceful shutdown in Node?
  • Difference between process.exit() and process.exitCode?

Security basics

Validate all input, never build commands or queries from strings, keep secrets out of code, and treat your dependencies as part of your attack surface.

  • Injection: use parameterized SQL queries; use execFile/spawn with an args array instead of exec with string concatenation.
  • Path traversal: resolve user paths against a root and check the result stays inside it.
  • Prototype pollution: deep-merging untrusted JSON can set __proto__ / constructor.prototype. Use schema validation, Object.create(null) or Map, and patched libraries.
  • DoS: limit body size, add timeouts and rate limits, avoid ReDoS-prone regexes, never do unbounded sync work on user input.
  • Secrets in env vars or a secret manager, never in git. Hash passwords with bcrypt, scrypt or argon2; compare secrets with crypto.timingSafeEqual.
  • Supply chain: npm audit, lockfiles, npm ci, few dependencies, --ignore-scripts when possible. Use security headers (Helmet) and CORS with an allow-list in HTTP apps.
  • The permission model (--permission, stable flag name since Node 24) can restrict file system, child process and worker access for a process.

Interview questions

  • What are common security risks in Node.js apps?
  • How do you safely run a shell command with user input?
  • What is prototype pollution?

Concurrency, scaling & production

child_process vs worker_threads vs cluster

child_process runs another program, worker_threads runs JavaScript in parallel threads inside one process, and cluster forks copies of your server to share one port.

  • child_process: spawn (streams output), exec (runs in a shell, buffers output), execFile (no shell), fork (a new Node process with an IPC channel). Separate memory, separate V8.
  • worker_threads: real threads in the same process, each with its own V8 isolate and event loop. Communicate with postMessage (structured clone), share memory with SharedArrayBuffer + Atomics, or transfer ArrayBuffers with zero copy.
  • cluster: the primary process forks N workers that all listen on the same port. The primary distributes connections (round-robin on everything except Windows).
  • Use workers for CPU-bound JavaScript (image resize, parsing, hashing). Use cluster (or many containers) to use all cores for an I/O server. Use child_process to run other binaries (ffmpeg, git).
  • Workers are expensive to start; use a pool (Piscina) instead of one worker per request.

Interview questions

  • Difference between worker_threads and cluster?
  • Difference between spawn, exec, execFile and fork?
  • How does cluster let multiple processes listen on the same port?
  • How do you share data between worker threads?

Scaling in production: PM2, load balancing, statelessness

Scale Node horizontally: one process per core or container, a load balancer in front, and no in-process state that has to be shared.

  • Vertical: one Node process uses one core for JavaScript. Use cluster or PM2 cluster mode to run one process per core on a VM.
  • Horizontal: run many instances (VMs, containers, pods) behind a load balancer (Nginx, HAProxy, cloud LB, Kubernetes Service).
  • PM2: process manager that restarts crashed apps, runs cluster mode (-i max), does zero-downtime reloads (pm2 reload), log handling and startup scripts.
  • Stateless instances: sessions in Redis or JWTs, uploads in object storage, caches in Redis, scheduled jobs with a distributed lock or a single scheduler.
  • WebSockets need sticky sessions or a pub/sub adapter (for example Redis) so messages reach users connected to other instances.
  • Offload slow work to queues (BullMQ, SQS, Kafka) and add caching, connection pooling and timeouts to downstream calls.

Interview questions

  • How do you scale a Node.js application?
  • What is PM2 and why use it?
  • Users connected over WebSockets to instance A miss messages sent from instance B. Why, and how do you fix it?

Memory leaks, GC & profiling

V8 frees what is unreachable; leaks are objects you still reference by mistake. Find them with heap snapshots and fix the reference.

  • V8 heap: new space (young objects, fast scavenge GC) and old space (survivors, mark-sweep-compact). Buffers live outside the heap.
  • Typical leaks: unbounded caches/Maps, global variables, listeners added per request, uncleared timers/intervals, closures holding big objects, and growing arrays of promises.
  • Signs: heap usage climbs after each GC, more frequent GC pauses, then FATAL ERROR: ... JavaScript heap out of memory.
  • Tools: process.memoryUsage(), --inspect + Chrome DevTools heap snapshots (compare two snapshots), --heapsnapshot-near-heap-limit, v8.writeHeapSnapshot(), Clinic.js, APM.
  • CPU profiling: node --cpu-prof app.js or --prof + --prof-process, then read flame graphs.
  • --max-old-space-size=<MB> raises the heap limit. It hides a leak; it does not fix it. In containers, set it relative to the memory limit.

Interview questions

  • How do you find a memory leak in a Node.js service?
  • What are common causes of memory leaks in Node?
  • What is the difference between heapUsed, heapTotal, rss and external?

Modern Node: 22, 24 & 26 LTS features

Recent LTS lines ship much of what used to need packages: a test runner, fetch, watch mode, .env loading, require(esm) and running TypeScript directly.

  • Release lines (Dec 2026): Node 26 is the Active LTS (since Oct 2026), 24 and 22 are Maintenance LTS, and 20 is end-of-life. From Node 27 there is one major per year and every major becomes LTS.
  • node:test + node:assert: built-in test runner (stable since 20) with describe/it, mocks, coverage (--experimental-test-coverage) and --test file discovery. In 24 subtests are awaited automatically.
  • fetch, WebSocket client, URLPattern (24), Temporal (26) are globals; --watch restarts on file changes (stable in 22); --env-file loads .env; node --run <script> runs package.json scripts quickly.
  • TypeScript type stripping: node app.ts works with no flag since 23.6 and 22.18; stable in 25.2 / 24.12. Only erasable syntax: no enum, no runtime namespace, no parameter properties; no type checking and tsconfig.json is ignored.
  • require(esm) without a flag since 22.12; fs.glob, util.parseArgs, util.styleText, AbortSignal.timeout, structuredClone round out the standard library.
  • Node 24 also brought V8 13.6 (RegExp.escape, Float16Array, using declarations), npm 11 and AsyncLocalStorage on AsyncContextFrame.

Interview questions

  • What notable features have recent Node LTS versions added?
  • Can Node.js run TypeScript directly now?
  • Which Node version should a new production project use?