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
- Node = V8 (runs JavaScript) + libuv (event loop, async I/O, thread pool) + C++ bindings + the JS standard library (
fs,http,stream...). - 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.
- Event loop phases: timers → pending callbacks → poll → check → close callbacks.
setTimeoutruns in timers, I/O callbacks in poll,setImmediatein check. - Priority after each callback:
process.nextTickqueue first, then promise microtasks, then the next macrotask. RecursivenextTickcan starve I/O. - Inside an I/O callback,
setImmediatealways runs beforesetTimeout(fn, 0). In the main module their order is not guaranteed. - Thread pool default size is 4; change it with the
UV_THREADPOOL_SIZEenv var before startup. Network I/O does not use the pool. - Blocking the loop: sync fs/crypto, huge
JSON.parse, catastrophic regex, long loops. Fix with async APIs, chunking withsetImmediate, or worker_threads. - CommonJS:
requireis sync, dynamic, cached, wraps each file in a function (exports, require, module, __filename, __dirname). ESM:importis static, async, live bindings, top-levelawait. - Module type:
.mjs= ESM,.cjs= CJS,.jsfollows"type"in the nearest package.json. Since 22.12require()can load sync ESM. - EventEmitter listeners run synchronously in registration order. An
'error'event with no listener throws. - 4 stream types: Readable, Writable, Duplex, Transform.
write()returningfalse= backpressure, wait for'drain'. Preferstream.pipelineover.pipe(it forwards errors and cleans up). - Buffer = fixed-size raw bytes (a
Uint8Arraysubclass).Buffer.allocis zero-filled;allocUnsafeis faster but may hold old memory. - Errors: error-first callbacks,
try/catcharoundawait,'error'events.uncaughtException/unhandledRejectionare last-resort loggers: log, then exit and let a supervisor restart. - CPU work → worker_threads. Another program → child_process. Use all CPU cores for a server → cluster / PM2 / several containers behind a load balancer.
^1.2.3allows minor + patch updates,~1.2.3allows patch only. Commit the lockfile and usenpm ciin CI.- Modern Node (22/24/26 LTS): built-in
node:test, globalfetch,--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 canrequireinside anif. Default for.jsfiles 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:
.mjsis ESM,.cjsis CJS,.jsfollows"type": "module"or"commonjs"in the nearest package.json. - ESM has no
__dirname,__filename,requireormodule. Useimport.meta.dirname/import.meta.filename(Node 20.11+) orimport.meta.url. - ESM can
importCJS (you getmodule.exportsas the default export). CJS can load ESM withawait import()and, since 22.12 / 20.19, withrequire()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
exportsandmodule.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'spackage.jsonmainorindex.js) → walk upnode_modulesfolders. - 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.cachekeyed by its resolved filename. Laterrequirecalls return the samemodule.exportsobject, 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 therequireinside the function that needs it.
Interview questions
- What is the module wrapper function?
- What happens when you
requirethe same module twice? - How does Node handle circular
requirecalls? - 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 installmay update the lockfile within ranges.npm cideletesnode_modules, installs exactly from the lockfile and fails if it disagrees with package.json — use it in CI and Docker.npxruns a package binary without installing it globally.npm run <script>runs a script withnode_modules/.binon the PATH.- Other tools: pnpm (content-addressed store, strict
node_modules), Yarn, and Corepack to pin the package manager version.
Interview questions
- Difference between
dependenciesanddevDependencies? - 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/setIntervalwhose 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:
setImmediatecallbacks, run right after poll. - close callbacks:
'close'events such assocket.on('close'). - After each callback Node empties the
process.nextTickqueue, 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
setImmediaterun beforesetTimeout(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.nextTickruns as soon as the current JavaScript operation finishes, before any promise callback. It is Node-only.- Microtasks (
.then,awaitcontinuations,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
setImmediateorqueueMicrotaskovernextTick; recursivenextTickstarves the event loop because I/O never gets a turn.
Interview questions
- Difference between
process.nextTickandsetImmediate? - Which runs first:
process.nextTickorPromise.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
fsAPIs (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; settingprocess.envinside the app is not reliable because the pool may already exist. - With 4 threads, the 5th concurrent
pbkdf2call waits in the queue. A slow disk or manydns.lookupcalls can delay unrelatedfswork. 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.createServeruse 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/stringifyof 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 toworker_threadsor 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
bcryptmakes 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.emitcalls listeners synchronously and returnstrueif there were any. UsesetImmediateorqueueMicrotaskinside 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
setMaxListenersonly 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.
Bufferis a subclass ofUint8Array, so typed-array methods work. Its memory lives outside the JS heap (counted inexternal/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.lengthis bytes, not characters.'é'is 2 bytes in UTF-8; useBuffer.byteLength(str).subarray/slicereturn a view sharing memory; changes show up in the original. Copy withBuffer.from(buf).
Interview questions
- What is a Buffer and why does Node need it?
- Difference between
Buffer.allocandBuffer.allocUnsafe? - Why can
buf.lengthdiffer fromstr.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')orfs.promises): non-blocking, works withawaitandPromise.all. Default choice in modern code. readFileloads the whole file into memory. For large files use streams (createReadStream) orFileHandle.readLines().fs.existsSyncis fine, but checking before opening is a race condition. Just open the file and handleENOENT.fs.watchuses OS notifications and is not consistent across platforms; tools like chokidar smooth it out.
Interview questions
- Difference between
fs.readFileandfs.readFileSync? - Difference between
fs.readFileandfs.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 callingpipeswitches to flowing;for await...ofis the modern way to consume. - Backpressure:
writable.write()returnsfalseonce the internal buffer reacheshighWaterMark. Stop writing and wait for'drain'. highWaterMarkdefault: 64 KiB for byte streams since Node 22 (16 KiB before), 16 objects in object mode.stream.pipeline(a, b, c, cb)orrequire('stream/promises').pipelinehandles 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 forfetchcompatibility.
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.pipelineover.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.
reqis anIncomingMessage(Readable):req.method,req.url,req.headers. The body arrives as a stream of chunks.resis aServerResponse(Writable):res.statusCode,res.setHeader,res.writeHead,res.write,res.end. Forgettingres.end()leaves the client hanging.- Parse URLs with the WHATWG
URLclass;url.parse()is deprecated. - Keep-alive connections are reused by default; tune
server.keepAliveTimeoutandheadersTimeoutbehind 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 checkerrfirst andreturnafter handling it. - Promises:
.catch()ortry/catcharoundawait. Atry/catchdoes 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 isthrow, 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
uncaughtExceptionandunhandledRejection? - Should you keep the process running after
uncaughtException? - Why doesn't
try/catchcatch an error thrown in asetTimeoutcallback?
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 = 1sets the exit code and lets pending work finish.process.exit(1)stops immediately, possibly cutting off async logging.--env-file=.envloads a dotenv file without thedotenvpackage (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()andprocess.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/spawnwith an args array instead ofexecwith 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)orMap, 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-scriptswhen 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 withSharedArrayBuffer+Atomics, or transferArrayBuffers 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,execFileandfork? - 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.jsor--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,rssandexternal?
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) withdescribe/it, mocks, coverage (--experimental-test-coverage) and--testfile discovery. In 24 subtests are awaited automatically.fetch,WebSocketclient,URLPattern(24),Temporal(26) are globals;--watchrestarts on file changes (stable in 22);--env-fileloads.env;node --run <script>runs package.json scripts quickly.- TypeScript type stripping:
node app.tsworks with no flag since 23.6 and 22.18; stable in 25.2 / 24.12. Only erasable syntax: noenum, no runtimenamespace, no parameter properties; no type checking andtsconfig.jsonis ignored. require(esm)without a flag since 22.12;fs.glob,util.parseArgs,util.styleText,AbortSignal.timeout,structuredCloneround out the standard library.- Node 24 also brought V8 13.6 (
RegExp.escape,Float16Array,usingdeclarations), npm 11 andAsyncLocalStorageonAsyncContextFrame.
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?