Node.js Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Which list shows the main phases of the Node.js event loop in order?
Correct answer: timers → pending callbacks → poll → check → close callbacks
Timers run
setTimeout/setIntervalcallbacks, poll waits for and runs I/O callbacks, check runssetImmediate, close runscloseevents. There is no render step: that's a browser concept.2. What is the order of the output?
setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); process.nextTick(() => console.log("nextTick")); console.log("sync");Correct answer: sync, nextTick, promise, timeout
Synchronous code runs first. Then Node.js drains the
process.nextTickqueue, then the promise microtask queue, and only then moves to the event loop phases with timers.3. Inside an I/O callback (for example, in
fs.readFile), which runs first?fs.readFile(__filename, () => { setTimeout(() => console.log("timeout"), 0); setImmediate(() => console.log("immediate")); });Correct answer:
immediate, alwaysAfter the poll phase the loop goes to the check phase, where
setImmediateruns, before it comes back to timers. In the main module (outside I/O) the order of the two is not guaranteed.4. Why can recursive
process.nextTickcalls be dangerous?Correct answer: The queue drains fully first, so endless ticks starve I/O
The same applies to an endless chain of microtasks.
setImmediatelets the event loop process I/O between iterations.5. What does the libuv thread pool handle by default?
Correct answer: File system work,
dns.lookup, somecryptoandzlibNetwork sockets use the OS's async mechanisms (epoll, kqueue, IOCP) and don't need the pool. The pool has 4 threads by default, configurable with
UV_THREADPOOL_SIZE.6. A request handler runs a CPU-heavy loop for 2 seconds. What happens to other requests?
Correct answer: They wait, as the event loop can't handle anything else
Move heavy CPU work to
worker_threads, a separate service or a job queue, or split it into small chunks withsetImmediatebetween them.7. Which of these can block the event loop?
Correct answer:
JSON.parseof a 200 MB stringWaiting for the network or disk does not block the loop. Large synchronous operations do: big
JSON.parse/stringify, sorting huge arrays, complex regex, sync crypto.8. How do you measure how busy the event loop is?
Correct answer: With
performance.eventLoopUtilization()ormonitorEventLoopDelay()Event loop delay and utilization are key metrics for a Node.js service. High delay means callbacks wait long before running, which users feel as latency.
9. What does
timer.unref()do?Correct answer: Lets the process exit with this timer still pending
Normally an active timer keeps the process alive.
unrefis useful for background tasks like periodic metrics that shouldn't prevent shutdown.ref()undoes it.10. What does
await setTimeout(1000)imported fromnode:timers/promisesdo?Correct answer: Waits about one second without blocking the event loop
node:timers/promiseshas promise versions ofsetTimeout,setImmediateandsetInterval(an async iterator). They also accept anAbortSignal.11. Why use streams to send a 2 GB file instead of
readFile?Correct answer: Streams use small chunks, so memory use stays low
readFileloads the whole file into memory first. Withfs.createReadStream(path).pipe(res)only a small buffer is in memory at any time.12. What are the four basic types of streams in Node.js?
Correct answer: Readable, Writable, Duplex, Transform
A TCP socket is Duplex (read and write). Transform is a Duplex that changes data as it passes through, like
zlib.createGzip().13. What is backpressure in streams?
Correct answer: A signal that the writable side can't keep up
writable.write()returnsfalsewhen its buffer is overhighWaterMark. Correct code waits for thedrainevent.pipe()andpipeline()do this for you.14. Why is
stream.pipeline()preferred over chaining.pipe()?Correct answer: It forwards errors and destroys all streams on failure
With
.pipe()an error in one stream doesn't close the others.await pipeline(src, transform, dest)fromnode:stream/promisesalso works withasync/await.15. How can you read a readable stream line by line or chunk by chunk with
async/await?Correct answer: With
for await (const chunk of stream)Readable streams are async iterables. For lines, combine it with
readline.createInterface({ input: stream }), which is also async iterable.16. What is a
Buffer?Correct answer: A fixed-length sequence of bytes
Buffers hold binary data: file contents, network packets, images. Convert with
buf.toString("utf8")orBuffer.from(text, "utf8").17. What is the difference between
Buffer.alloc(10)andBuffer.allocUnsafe(10)?Correct answer:
alloczeroes memory;allocUnsafemay contain old dataUse
allocUnsafeonly if you immediately overwrite every byte. Otherwise you might leak sensitive data that was previously in that memory.18. What does
Buffer.from("привіт").lengthreturn?Correct answer: 12
lengthis in bytes, not characters. Each Cyrillic letter takes 2 bytes in UTF-8.Buffer.byteLength(str)gives the byte size without creating a buffer.19. What is
objectModein streams?Correct answer: A stream passes any JS values, not only strings and Buffers
In object mode,
highWaterMarkcounts objects instead of bytes. It's useful for pipelines of records, such as rows from a database.20. How do you gzip a file with streams?
import { createReadStream, createWriteStream } from "node:fs"; import { createGzip } from "node:zlib"; import { pipeline } from "node:stream/promises";Correct answer:
await pipeline(createReadStream("a.log"), createGzip(), createWriteStream("a.log.gz"))createGzip()is a Transform stream. The whole file is never in memory, andpipelinehandles errors and cleanup.21. What happens if an
EventEmitteremitserrorand there is noerrorlistener?Correct answer: The error is thrown, which usually crashes the process
The
errorevent is special. Always add anerrorlistener to streams, sockets and servers, or usepipelineandevents.once, which turn it into a rejection.22. What does the warning
MaxListenersExceededWarningusually point to?Correct answer: A likely memory leak: listeners keep being added
The default limit is 10 listeners per event. Raising it with
setMaxListenershides the problem; usually you should remove listeners withoffor useonce.23. How do you wait for one event as a promise?
Correct answer:
const [value] = await once(emitter, "ready")events.onceresolves with the event arguments and rejects if the emitter emitserrorfirst.events.ongives an async iterator for many events.24. What is the difference between operational errors and programmer errors?
Correct answer: Operational errors are expected failures; programmer errors are bugs
Operational errors should be handled: retry, return 4xx/5xx, log. Bugs should be fixed; after an unexpected exception the safest move is often to restart the process.
25. Why is it useful to pass
causewhen re-throwing an error?try { await db.query(sql); } catch (err) { throw new Error("Failed to load orders", { cause: err }); }Correct answer: It adds context while keeping the original error
Node.js prints the cause chain in stack traces. You get both the business context and the low-level reason.
26. What is
AbortControllerused for in Node.js?Correct answer: Cancelling async operations through an
AbortSignalMany Node.js APIs accept
{ signal }.AbortSignal.timeout(5000)creates a signal that aborts after 5 seconds, which is a simple way to add timeouts.27. Why should every outgoing HTTP call have a timeout?
Correct answer: A slow dependency can hold requests open indefinitely
For example,
fetch(url, { signal: AbortSignal.timeout(3000) }). Combine timeouts with limited retries and backoff for transient errors.28. How do you define error-handling middleware in Express?
Correct answer: A function with four parameters:
(err, req, res, next)Express recognizes error handlers by their four parameters. Register them after all routes. Calling
next(err)skips regular middleware and jumps to them.29. What changed in Express 5 for
asyncroute handlers?Correct answer: Rejected promises are passed to
next(err)automaticallyIn Express 4 a rejection in an async handler was unhandled unless you wrapped it with try/catch or a helper like
express-async-handler.30. Does the order of
app.use()calls matter in Express?Correct answer: Yes, they run in the order they are registered
For example,
express.json()must be registered before routes that readreq.body, and the error handler must be last.31. What is
express.Router()used for?Correct answer: Grouping related routes into a mountable module
For example, a
usersrouter mounted withapp.use("/users", usersRouter). It keeps large apps organized.32. What is a key feature of Fastify compared with Express?
Correct answer: JSON Schema validation and an encapsulated plugin system
Fastify compiles schemas into fast validators and serializers, logs with Pino by default and uses hooks (
onRequest,preHandler, ...) for the request lifecycle.33. Why validate request input on the server even if the front end already validates it?
Correct answer: Anyone can send requests directly, bypassing the UI
Validate types, lengths and formats with a schema library (Zod, JSON Schema, Valibot) at the API boundary, and reject unknown fields.
34. Which HTTP methods are idempotent by definition?
Correct answer: GET, PUT, DELETE (and HEAD, OPTIONS)
Repeating an idempotent request has the same effect as doing it once, so clients can safely retry it. For POST, idempotency keys give the same safety.
35. What is a good way to return API errors in a consistent format?
Correct answer: A stable JSON structure, such as RFC 9457 Problem Details
Use correct status codes and a predictable error body. Never send stack traces or internal messages to clients in production.
36. How do you serve a folder of static files in Express?
Correct answer:
app.use(express.static("public"))express.staticsets content types and caching headers and handles ranges. In production, static files are often served by a CDN or a reverse proxy instead.37. How should passwords be stored?
Correct answer: Hashed with a slow, salted algorithm like Argon2id, scrypt or bcrypt
Fast hashes like SHA-256 can be brute-forced quickly on GPUs. Node.js has
crypto.scryptbuilt in; Argon2 and bcrypt are available as packages.38. What does a JWT signature guarantee?
Correct answer: The token wasn't changed; it doesn't hide the payload
The payload is only Base64URL-encoded, so don't put secrets in it. Always verify the signature with a fixed algorithm list and check
exp.39. What is a common downside of JWTs compared with server-side sessions?
Correct answer: They're hard to revoke before they expire
Common solutions are short-lived access tokens with refresh tokens, or a deny list. Sessions in a store like Redis can be deleted instantly.
40. Which cookie attributes help protect a session cookie?
Correct answer:
HttpOnly,SecureandSameSiteHttpOnlyhides the cookie from JavaScript (limits XSS damage),Securesends it only over HTTPS andSameSitehelps against CSRF.41. Why must SQL queries use parameters instead of string concatenation?
// Bad db.query("SELECT * FROM users WHERE email = '" + email + "'"); // Good db.query("SELECT * FROM users WHERE email = $1", [email]);Correct answer: Parameters go separately, so input can't change the query
ORMs and query builders parameterize for you, but raw queries built from strings are still vulnerable.
42. What does the
helmetmiddleware do?Correct answer: Sets security-related HTTP response headers
It's a quick way to apply sensible header defaults in Express. It doesn't replace input validation, authentication or rate limiting.
43. Why add rate limiting to a login endpoint?
Correct answer: To slow down brute-force and stuffing attacks
Limit attempts per IP and per account. With several server instances, keep the counters in a shared store like Redis.
44. How do you generate a cryptographically secure random token?
Correct answer:
crypto.randomBytes(32).toString("hex")Math.random()is predictable and must not be used for tokens, session IDs or password reset links.45. How should you compare a secret token from a request with the stored one?
Correct answer: With
crypto.timingSafeEqualon equal-length buffers===stops at the first different character, so response time can leak how much of the token was correct. A constant-time comparison avoids that.46. Why do Node.js apps use a database connection pool?
Correct answer: Opening connections is slow, so a pool reuses open ones
Size the pool for the database's limits. Always release a checked-out client, even on errors, or the pool runs dry and requests hang.
47. What is the N+1 query problem?
Correct answer: One query for a list, plus one more query per item
For 100 posts it means 101 queries. Fix it with a JOIN,
WHERE id IN (...)or batching (e.g. DataLoader in GraphQL).48. When do you need a database transaction?
Correct answer: When several changes must succeed or fail together
Use the same connection for every statement in the transaction and roll back on any error.
49. What is an ORM such as Prisma or TypeORM?
Correct answer: A library that maps tables to objects and builds queries
ORMs speed up common work and add type safety, but it's easy to write slow queries without seeing the SQL. Query builders like Kysely or Drizzle are a lighter middle ground.
50. Which Node.js version feature lets you use SQLite without installing a package?
Correct answer: The
node:sqlitemodulenode:sqliteprovides a synchronousDatabaseSyncAPI. It's handy for scripts, tests and small apps.51. What are worker threads for?
Correct answer: Running CPU-heavy JavaScript in parallel
Each worker has its own V8 instance and event loop. Communicate with
postMessage; large binary data can be transferred or shared withSharedArrayBuffer.52. What is the difference between
child_process.execandchild_process.spawn?Correct answer:
execuses a shell and buffers output;spawnstreams itUse
spawnorexecFilefor large output or untrusted arguments. Passing user input toexecrisks command injection.53. What does
child_process.fork()do?Correct answer: Starts a new Node.js process with an IPC channel
Forked processes don't share memory with the parent. It's the basis of the
clustermodule.54. What does the
clustermodule do?Correct answer: Runs several processes sharing a port, to use all cores
In containers, a common alternative is one process per container and scaling with more containers (Kubernetes, Docker Swarm) or a process manager like PM2.
55. How do you mock a function with the built-in test runner?
Correct answer:
const fn = mock.fn()fromnode:testnode:testalso hasmock.methodfor object methods,mock.timersfor fake timers and module mocking.56. How do you test an Express app's endpoints without starting a real server on a fixed port?
Correct answer: Pass
appto Supertest, or start it on port 0Port 0 lets the OS pick a free port, so tests can run in parallel. Export the app separately from the
listen()call to make this easy.57. Which
node:assertfunction compares objects by their contents?Correct answer:
assert.deepStrictEqualstrictEqualusesObject.is, so two different objects with the same content are not equal. Import fromnode:assert/strictto get strict versions by default.58. What does the Twelve-Factor App recommend for configuration?
Correct answer: Store config in environment variables, separate from code
The same build can then run in staging and production with different settings. Validate the config at startup and fail fast if something is missing.
59. What should a Node.js server do when it receives
SIGTERM?Correct answer: Stop accepting connections, finish requests, then exit
Orchestrators like Kubernetes send
SIGTERMbefore killing a pod.server.close()stops new connections; add a timeout in case something hangs.60. Why should logs include a request ID?
Correct answer: To find all the log lines of a single request
Generate or accept a request ID, pass it to downstream calls in a header and add it to every log line, for example with
AsyncLocalStorage.61. Which data must never be written to logs?
Correct answer: Passwords, tokens and full card numbers
Logs are copied to many systems and kept a long time. Pino supports
redactpaths to remove sensitive fields automatically.62. In a Dockerfile for a Node.js app, why copy
package.jsonand the lock file before the source code?COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY . .Correct answer: So Docker can cache the
npm cilayerEach instruction is a cached layer. Also run as a non-root user, use a small base image and add a
.dockerignorefornode_modules.63. What is a health check endpoint like
/healthused for?Correct answer: It tells load balancers if an instance can take traffic
Kubernetes distinguishes liveness (should it be restarted?) and readiness (can it take traffic now?). Readiness can check dependencies like the database.
64. What does the
exportsfield inpackage.jsondo?Correct answer: Defines public entry points and blocks internal imports
With
exports,import "pkg/internal/x"fails unless that path is listed. It also supports conditions likeimport,requireandtypes.65. Can CommonJS code
require()an ES module in modern Node.js?Correct answer: Yes, if the ES module has no top-level
awaitrequire(esm)was added in recent versions, which made mixing module systems much easier. If the module uses top-levelawait, use dynamicimport().66. What does the
enginesfield inpackage.jsonexpress?Correct answer: The Node.js and npm versions it supports
npm warns when versions don't match; with
engine-strictit refuses to install. Many projects also add.nvmrcor apackageManagerfield.67. What are npm workspaces?
Correct answer: Managing several packages in one repository
Define
"workspaces": ["packages/*"]in the rootpackage.json. pnpm and Yarn have similar features.68. What is a risk of
postinstallscripts in dependencies?Correct answer: They run arbitrary code during install
Pin versions with a lock file, review new dependencies and consider
--ignore-scriptsor an allow list for packages that really need install scripts.69. When are Server-Sent Events (SSE) a better choice than WebSockets?
Correct answer: When only the server pushes updates, over plain HTTP
SSE uses a normal HTTP response with
Content-Type: text/event-stream. The browser'sEventSourcereconnects automatically. WebSockets are full duplex.70. What is a challenge of WebSockets with several server instances?
Correct answer: Each connection lives on one instance, so broadcasts need Redis
Libraries like Socket.IO provide adapters (Redis and others) for broadcasting across instances. Load balancers may also need sticky sessions for some transports.
71. Why use a job queue like BullMQ for sending emails after sign-up?
Correct answer: The API responds fast, and failed jobs are retried
Slow or unreliable work goes to a background worker. Jobs should be idempotent, since a retry can repeat a job that partly succeeded.
72. What is
AsyncLocalStorageused for?Correct answer: Keeping per-request data across
awaits and callbacksCall
storage.run(context, handler)at the start of a request; any code it calls, sync or async, can read the context withstorage.getStore().73. Why does HTTP keep-alive matter for a service that calls other APIs a lot?
Correct answer: Reusing connections avoids a new handshake for each request
The global
fetch(undici) and the defaulthttpagent in modern Node.js reuse connections. Very high request rates may still need tuning of the connection pool.74. Why is cursor-based pagination often better than
OFFSETfor large tables?Correct answer:
OFFSETskips rows and shifts; a cursor uses an indexPage 10,000 with
OFFSETscans everything before it. The trade-off: cursors can't jump straight to page N.75. What is the cache-aside pattern with Redis?
Correct answer: Read the cache; on a miss, load from the DB and store it
On updates, delete or refresh the cached key. A TTL limits how stale data can get, and caching only hot keys keeps memory under control.