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. 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/setInterval callbacks, poll waits for and runs I/O callbacks, check runs setImmediate, close runs close events. There is no render step: that's a browser concept.

  2. 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.nextTick queue, then the promise microtask queue, and only then moves to the event loop phases with timers.

  3. 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, always

    After the poll phase the loop goes to the check phase, where setImmediate runs, before it comes back to timers. In the main module (outside I/O) the order of the two is not guaranteed.

  4. 4. Why can recursive process.nextTick calls be dangerous?

    Correct answer: The queue drains fully first, so endless ticks starve I/O

    The same applies to an endless chain of microtasks. setImmediate lets the event loop process I/O between iterations.

  5. 5. What does the libuv thread pool handle by default?

    Correct answer: File system work, dns.lookup, some crypto and zlib

    Network 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. 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 with setImmediate between them.

  7. 7. Which of these can block the event loop?

    Correct answer: JSON.parse of a 200 MB string

    Waiting 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. 8. How do you measure how busy the event loop is?

    Correct answer: With performance.eventLoopUtilization() or monitorEventLoopDelay()

    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. 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. unref is useful for background tasks like periodic metrics that shouldn't prevent shutdown. ref() undoes it.

  10. 10. What does await setTimeout(1000) imported from node:timers/promises do?

    Correct answer: Waits about one second without blocking the event loop

    node:timers/promises has promise versions of setTimeout, setImmediate and setInterval (an async iterator). They also accept an AbortSignal.

  11. 11. Why use streams to send a 2 GB file instead of readFile?

    Correct answer: Streams use small chunks, so memory use stays low

    readFile loads the whole file into memory first. With fs.createReadStream(path).pipe(res) only a small buffer is in memory at any time.

  12. 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. 13. What is backpressure in streams?

    Correct answer: A signal that the writable side can't keep up

    writable.write() returns false when its buffer is over highWaterMark. Correct code waits for the drain event. pipe() and pipeline() do this for you.

  14. 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) from node:stream/promises also works with async/await.

  15. 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. 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") or Buffer.from(text, "utf8").

  17. 17. What is the difference between Buffer.alloc(10) and Buffer.allocUnsafe(10)?

    Correct answer: alloc zeroes memory; allocUnsafe may contain old data

    Use allocUnsafe only if you immediately overwrite every byte. Otherwise you might leak sensitive data that was previously in that memory.

  18. 18. What does Buffer.from("привіт").length return?

    Correct answer: 12

    length is 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. 19. What is objectMode in streams?

    Correct answer: A stream passes any JS values, not only strings and Buffers

    In object mode, highWaterMark counts objects instead of bytes. It's useful for pipelines of records, such as rows from a database.

  20. 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, and pipeline handles errors and cleanup.

  21. 21. What happens if an EventEmitter emits error and there is no error listener?

    Correct answer: The error is thrown, which usually crashes the process

    The error event is special. Always add an error listener to streams, sockets and servers, or use pipeline and events.once, which turn it into a rejection.

  22. 22. What does the warning MaxListenersExceededWarning usually point to?

    Correct answer: A likely memory leak: listeners keep being added

    The default limit is 10 listeners per event. Raising it with setMaxListeners hides the problem; usually you should remove listeners with off or use once.

  23. 23. How do you wait for one event as a promise?

    Correct answer: const [value] = await once(emitter, "ready")

    events.once resolves with the event arguments and rejects if the emitter emits error first. events.on gives an async iterator for many events.

  24. 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. 25. Why is it useful to pass cause when 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. 26. What is AbortController used for in Node.js?

    Correct answer: Cancelling async operations through an AbortSignal

    Many 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. 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. 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. 29. What changed in Express 5 for async route handlers?

    Correct answer: Rejected promises are passed to next(err) automatically

    In 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. 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 read req.body, and the error handler must be last.

  31. 31. What is express.Router() used for?

    Correct answer: Grouping related routes into a mountable module

    For example, a users router mounted with app.use("/users", usersRouter). It keeps large apps organized.

  32. 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. 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. 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. 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. 36. How do you serve a folder of static files in Express?

    Correct answer: app.use(express.static("public"))

    express.static sets content types and caching headers and handles ranges. In production, static files are often served by a CDN or a reverse proxy instead.

  37. 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.scrypt built in; Argon2 and bcrypt are available as packages.

  38. 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. 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. 40. Which cookie attributes help protect a session cookie?

    Correct answer: HttpOnly, Secure and SameSite

    HttpOnly hides the cookie from JavaScript (limits XSS damage), Secure sends it only over HTTPS and SameSite helps against CSRF.

  41. 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. 42. What does the helmet middleware 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. 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. 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. 45. How should you compare a secret token from a request with the stored one?

    Correct answer: With crypto.timingSafeEqual on 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. 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. 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. 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. 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. 50. Which Node.js version feature lets you use SQLite without installing a package?

    Correct answer: The node:sqlite module

    node:sqlite provides a synchronous DatabaseSync API. It's handy for scripts, tests and small apps.

  51. 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 with SharedArrayBuffer.

  52. 52. What is the difference between child_process.exec and child_process.spawn?

    Correct answer: exec uses a shell and buffers output; spawn streams it

    Use spawn or execFile for large output or untrusted arguments. Passing user input to exec risks command injection.

  53. 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 cluster module.

  54. 54. What does the cluster module 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. 55. How do you mock a function with the built-in test runner?

    Correct answer: const fn = mock.fn() from node:test

    node:test also has mock.method for object methods, mock.timers for fake timers and module mocking.

  56. 56. How do you test an Express app's endpoints without starting a real server on a fixed port?

    Correct answer: Pass app to Supertest, or start it on port 0

    Port 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. 57. Which node:assert function compares objects by their contents?

    Correct answer: assert.deepStrictEqual

    strictEqual uses Object.is, so two different objects with the same content are not equal. Import from node:assert/strict to get strict versions by default.

  58. 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. 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 SIGTERM before killing a pod. server.close() stops new connections; add a timeout in case something hangs.

  60. 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. 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 redact paths to remove sensitive fields automatically.

  62. 62. In a Dockerfile for a Node.js app, why copy package.json and 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 ci layer

    Each instruction is a cached layer. Also run as a non-root user, use a small base image and add a .dockerignore for node_modules.

  63. 63. What is a health check endpoint like /health used 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. 64. What does the exports field in package.json do?

    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 like import, require and types.

  65. 65. Can CommonJS code require() an ES module in modern Node.js?

    Correct answer: Yes, if the ES module has no top-level await

    require(esm) was added in recent versions, which made mixing module systems much easier. If the module uses top-level await, use dynamic import().

  66. 66. What does the engines field in package.json express?

    Correct answer: The Node.js and npm versions it supports

    npm warns when versions don't match; with engine-strict it refuses to install. Many projects also add .nvmrc or a packageManager field.

  67. 67. What are npm workspaces?

    Correct answer: Managing several packages in one repository

    Define "workspaces": ["packages/*"] in the root package.json. pnpm and Yarn have similar features.

  68. 68. What is a risk of postinstall scripts in dependencies?

    Correct answer: They run arbitrary code during install

    Pin versions with a lock file, review new dependencies and consider --ignore-scripts or an allow list for packages that really need install scripts.

  69. 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's EventSource reconnects automatically. WebSockets are full duplex.

  70. 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. 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. 72. What is AsyncLocalStorage used for?

    Correct answer: Keeping per-request data across awaits and callbacks

    Call storage.run(context, handler) at the start of a request; any code it calls, sync or async, can read the context with storage.getStore().

  73. 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 default http agent in modern Node.js reuse connections. Very high request rates may still need tuning of the connection pool.

  74. 74. Why is cursor-based pagination often better than OFFSET for large tables?

    Correct answer: OFFSET skips rows and shifts; a cursor uses an index

    Page 10,000 with OFFSET scans everything before it. The trade-off: cursors can't jump straight to page N.

  75. 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.