Autocoder

Node.js Interview Questions and Answers (Node 22)

Last updated 2026-11-19

Node.js interviews test whether you understand what the runtime does when your code is not running: the event loop, the libuv thread pool, streams and backpressure. Interviewers also check practical habits such as handling errors in async code, shutting down cleanly and keeping the loop free from blocking work. This page covers those topics for Node 22, the current long-term support line.

Answers lean on built-in capabilities now available without packages, including global fetch, the test runner and loading env files with a flag. If your target team uses Express, read the Express.js interview questions too, and for JavaScript language topics see how to crack a JavaScript interview.

Version coveredNode.js 22 (LTS)
Core topicsEvent loop, streams, modules, concurrency, errors, performance
Questions here18

What is built in now

Several things that once needed packages ship with Node 22. Interviewers like candidates who know this, because it signals current practice.

A scenario they like

"Your API p99 latency spikes every few minutes. Where do you look?" Good answers check for synchronous CPU work on the main thread such as JSON parsing of huge bodies or regular expressions, measure event loop delay with perf_hooks, look at garbage collection pauses, and check the thread pool for saturation by file system or crypto calls.

Node.js Interview Questions and Answers (Node 22): questions with worked answers

  1. 1

    What is Node.js and why is it good for I/O-bound workloads?

    easy

    Node.js is a JavaScript runtime built on the V8 engine and libuv. It runs your code on one main thread with a non-blocking, event-driven model, so while one request waits on the network or disk, the loop serves others. This suits APIs, proxies and real-time services that mostly wait. It is a poor fit for heavy CPU work on the main thread, which blocks every request.

  2. 2

    Describe the phases of the event loop.

    medium

    Each loop iteration goes through timers (setTimeout and setInterval callbacks), pending callbacks, idle and prepare, poll (retrieve I/O events and run their callbacks), check (setImmediate callbacks) and close callbacks. Between callbacks, Node drains process.nextTick and then promise microtasks. Inside an I/O callback, setImmediate always runs before a zero-delay setTimeout.

  3. 3

    What is the order of process.nextTick, promises, setTimeout and setImmediate?

    medium

    Synchronous code first. Then the nextTick queue, then promise microtasks, then timers or check-phase callbacks. The nextTick queue runs before promise callbacks, and recursive nextTick calls can starve I/O. From the main module the order of setTimeout 0 versus setImmediate is not deterministic.

    javascript
    setTimeout(() => console.log('timeout'), 0);
    setImmediate(() => console.log('immediate'));
    Promise.resolve().then(() => console.log('promise'));
    process.nextTick(() => console.log('tick'));
    console.log('sync');
    // sync, tick, promise, then timeout/immediate (order varies)
  4. 4

    What is the libuv thread pool and what uses it?

    medium

    libuv keeps a pool of four threads by default, set with UV_THREADPOOL_SIZE, for work that has no non-blocking OS API: file system operations, DNS lookups through getaddrinfo, and some crypto such as pbkdf2 and scrypt, plus zlib. Network sockets do not use it, since they rely on the OS notification mechanism. A saturated pool makes unrelated file or hashing calls queue up.

  5. 5

    What are streams and what is backpressure?

    medium

    Streams process data in chunks instead of loading everything into memory. Readable, Writable, Duplex and Transform are the four types. Backpressure occurs when a writable consumes slower than a readable produces. Writable.write returns false when its buffer is full, and you should wait for the drain event. stream.pipeline handles this and propagates errors and cleanup.

    javascript
    import { pipeline } from 'node:stream/promises';
    import { createReadStream, createWriteStream } from 'node:fs';
    import { createGzip } from 'node:zlib';
    
    await pipeline(
      createReadStream('big.log'),
      createGzip(),
      createWriteStream('big.log.gz'),
    );
  6. 6

    CommonJS versus ES modules in Node 22?

    medium

    CommonJS uses require and module.exports, loads synchronously and is the default for .js files unless package.json has type module. ES modules use import and export, support top-level await and load asynchronously. File extensions .mjs and .cjs force a format. ESM has no __dirname, so use import.meta.dirname, available in Node 20.11 and later. From 22.12, require() can load a synchronous ES module graph.

  7. 7

    How do you handle errors in async code?

    medium

    Use try/catch around await, attach catch to promises, and never leave a promise unhandled: since Node 15 an unhandled rejection crashes the process by default. For callback APIs, the first argument is the error. Emitters need an error listener or an unhandled error event throws. Log unhandledRejection and uncaughtException for visibility, but treat them as fatal, flush logs and exit so a supervisor restarts the process.

  8. 8

    How does EventEmitter work, and what is a common mistake?

    medium

    An EventEmitter keeps a map of event names to listener lists. on adds a listener, once removes it after the first call, and emit calls listeners synchronously in order. Common mistakes: forgetting to remove listeners, which leaks memory and triggers the MaxListenersExceeded warning, and emitting error with no listener, which throws.

    javascript
    import { EventEmitter } from 'node:events';
    const bus = new EventEmitter();
    bus.once('ready', (n) => console.log('ready', n));
    bus.on('error', (e) => console.error(e));
    bus.emit('ready', 1);
  9. 9

    When should you use worker threads versus cluster versus child_process?

    medium

    worker_threads run JavaScript in separate threads with their own event loop in the same process and can share memory through SharedArrayBuffer, which suits CPU-heavy tasks like image processing. cluster forks several processes sharing one port, using all CPU cores for an HTTP server. child_process spawns separate programs or Node scripts and communicates through pipes or IPC. In production, a container orchestrator often replaces cluster.

    javascript
    import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
    if (isMainThread) {
      const w = new Worker(new URL(import.meta.url), { workerData: 40 });
      w.on('message', (v) => console.log('fib', v));
    } else {
      const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
      parentPort.postMessage(fib(workerData));
    }
  10. 10

    How do you read configuration and secrets in Node 22?

    medium

    Read them from process.env, which holds strings only. Node 22 loads a file with node --env-file=.env app.js, so dotenv is optional. Validate on startup with a schema and fail fast if something is missing. Never commit .env files, and use the platform secret store in production. Convert numbers and booleans explicitly, because "false" is a truthy string.

  11. 11

    How do you do graceful shutdown?

    medium

    On SIGTERM, stop accepting new connections with server.close, let in-flight requests finish, close database pools and queues, then exit. Set a timeout so a stuck connection cannot block forever, and call server.closeIdleConnections to release keep-alive sockets. Container platforms send SIGTERM and then SIGKILL after a grace period, so the handler should be quick.

    javascript
    process.on('SIGTERM', () => {
      server.close(async () => {
        await db.end();
        process.exit(0);
      });
      server.closeIdleConnections();
      setTimeout(() => process.exit(1), 10_000).unref();
    });
  12. 12

    What is a Buffer?

    medium

    A Buffer is a fixed-size chunk of raw binary memory, a subclass of Uint8Array, used for files, sockets and encodings. Buffer.from(string, encoding) creates one and buf.toString(encoding) reads it. Buffer.alloc zero-fills memory, while the old new Buffer() constructor is deprecated because it could expose uninitialised memory. Use base64, hex and utf8 conversions carefully with multi-byte characters.

  13. 13

    How do you find and fix a memory leak in a Node service?

    hard

    Watch heap usage over time with process.memoryUsage or metrics. Reproduce under load, take heap snapshots with --inspect and Chrome DevTools or v8.writeHeapSnapshot at intervals, and compare retained objects. Typical causes are unbounded in-memory caches, listeners that are never removed, global arrays, closures holding large objects and timers never cleared. Fix by bounding caches with an LRU, removing listeners and clearing timers.

  14. 14

    How do you detect event loop blocking?

    hard

    Measure event loop delay with perf_hooks.monitorEventLoopDelay and alert on high percentiles. Profile with --cpu-prof or clinic to find the synchronous work, which is often JSON.parse on huge bodies, catastrophic regular expressions, synchronous crypto or fs calls, or big loops. Fix by streaming, chunking work with setImmediate, moving CPU work to a worker thread, or using async variants of APIs.

    javascript
    import { monitorEventLoopDelay } from 'node:perf_hooks';
    const h = monitorEventLoopDelay({ resolution: 20 });
    h.enable();
    setInterval(() => {
      console.log('p99 delay ms', h.percentile(99) / 1e6);
      h.reset();
    }, 5000);
  15. 15

    What is AsyncLocalStorage and why use it?

    hard

    AsyncLocalStorage keeps a value, such as a request ID or user, available across the entire async call chain without passing it through every function. You run a function inside als.run(store, fn), and any code it calls, including after awaits, can read als.getStore(). It is the basis for request-scoped logging and tracing. It has a small performance cost, so use one instance per concern.

  16. 16

    How would you write a safe HTTP request with the built-in fetch?

    hard

    fetch does not reject on HTTP error statuses, so check response.ok. It has no default timeout, so pass AbortSignal.timeout(ms). Parse the body only once, and handle network errors with catch. Retry only idempotent calls, with backoff. Use undici directly when you need connection pooling control or dispatchers.

    javascript
    const res = await fetch('https://api.example.com/items', {
      signal: AbortSignal.timeout(5000),
      headers: { accept: 'application/json' },
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const items = await res.json();
  17. 17

    How do you test Node code without extra libraries?

    hard

    Node 22 includes node:test with describe, it, mock and a built-in coverage flag, and node:assert for assertions. Run with node --test, and use --watch during development. Mock timers with mock.timers and functions with mock.fn. For HTTP, start the server on port 0 and call it with fetch. Many teams still use Vitest or Jest for richer tooling.

    javascript
    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    
    test('adds', () => {
      assert.equal(1 + 2, 3);
    });
  18. 18

    How do you secure a Node.js application?

    hard

    Validate all input with a schema, use parameterised queries, escape output, set security headers with helmet, rate limit, keep dependencies updated and audited with npm audit and lockfiles, run as a non-root user, and never pass user input to child_process.exec, eval or require. Store secrets outside the repo, and use HttpOnly cookies. See web security and OWASP interview questions.

Frequently asked questions

Which Node.js version should I prepare for?

Node 22, the current LTS line, while knowing that many teams still run 18 or 20. Mention which features need newer versions, such as require of ESM or the built-in watch mode.

Is Node.js single-threaded?

Your JavaScript runs on one main thread, but the runtime uses a libuv thread pool, V8 helper threads and optional worker threads, so Node as a whole is not single-threaded.

Do I need Express for Node interviews?

Most backend Node roles expect Express or a comparable framework such as Fastify or NestJS, but a fundamentals round tests plain Node first.

What coding problems are typical?

Implementing a rate limiter, promise utilities like a concurrency-limited map, a stream transform, an LRU cache, and a small REST endpoint with validation.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section