Skip to the content.

Node.js Interview Questions and Answers (with Runnable Code)

nodejs-interview-questions is a practical set of Node.js interview questions with clear answers and runnable JavaScript examples, for backend and full-stack developers preparing for junior, mid-level and senior Node.js interviews. It covers the event loop, async/await and promises, CommonJS vs ES modules, streams and buffers, EventEmitter, HTTP servers, worker threads and child processes, error handling, performance and memory leaks, security, testing with node:test, and common coding exercises like a concurrency-limited promise pool, debounce, throttle, LRU cache and rate limiter.

Every code exercise lives in examples/ and is tested in test/ with the built-in test runner. No dependencies.

Last reviewed: December 2026. Version notes refer to Node.js 22, 24 and 26 (the LTS lines in use as of this date). Check the official release schedule for the current status.

git clone https://github.com/Ralpberry-Labs/nodejs-interview-questions
cd nodejs-interview-questions
npm test            # runs node --test, Node 22+
node examples/event-loop-order.cjs

Table of Contents

How to Use This


1. Fundamentals

Q1. What is Node.js? [J]

A JavaScript runtime for running JS outside the browser. It combines:

Node is not a language and not a framework. Express, Fastify and NestJS are frameworks built on it.

Q2. Is Node.js single-threaded? [J]

Your JavaScript runs on one main thread, one call stack at a time. Node itself is not single-threaded:

A good answer: “single-threaded for my code, multi-threaded under the hood, and the design goal is that the main thread never waits”.

Q3. What does non-blocking I/O mean? [J]

The call starts the operation and returns immediately; the result is delivered later through a callback, promise or event. Compare:

import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';

const a = readFileSync('big.json');        // blocks the thread until done
const b = await readFile('big.json');      // this function pauses; the thread keeps serving others

In a server, one readFileSync per request means every other request waits. In a CLI script that runs once, sync calls are fine and simpler.

Q4. What is Node.js good at, and what is it bad at? [J]

Good: I/O-heavy work with many concurrent connections (APIs, gateways, real-time apps with WebSockets, BFFs, streaming, CLIs, tooling). One language across front end and back end, huge package ecosystem.

Weaker: long CPU-bound work on the main thread (image processing, big JSON transforms, heavy crypto, ML inference). It blocks the event loop. Mitigate with worker threads, native addons, a job queue, or a different service.

Q5. What is the difference between global, globalThis and window? [J]

globalThis is the standard name for the global object in every JS environment. In Node it equals global; in browsers it equals window. Use globalThis in code that must run everywhere. Note that top-level var in a CommonJS file does not create a global, because each module is wrapped in a function.

Q6. Which globals are specific to Node? [J]

process, Buffer, global, setImmediate, queueMicrotask (also in browsers), structuredClone (also in browsers) and, in CommonJS only: require, module, exports, __filename, __dirname. Node also exposes web-standard globals: fetch, URL, AbortController, TextEncoder, Blob, WebSocket (client), crypto.subtle, performance.

Q7. What is process? Name useful properties. [J]

The current Node process: process.argv (CLI arguments), process.env (environment variables, always strings), process.exit(code), process.exitCode, process.cwd(), process.pid, process.platform, process.memoryUsage(), process.hrtime.bigint(), process.nextTick(), process.on('SIGTERM', ...), process.stdin/stdout/stderr.

Prefer setting process.exitCode = 1 over calling process.exit(1), so pending output and async work can finish.

Q8. What is the REPL? [J]

Read-Eval-Print Loop: run node with no arguments. Useful commands: .help, .editor (multi-line), .load file.js, _ (last result). It supports top-level await.


2. The Event Loop

Q9. Explain the event loop. [M]

The event loop is how Node runs callbacks when their work is ready. JS runs until the call stack is empty; then the loop picks the next callback. libuv’s loop has phases, each with its own queue:

  1. timers: callbacks from setTimeout / setInterval whose time has passed.
  2. pending callbacks: some system-level callbacks deferred from the previous iteration (for example certain TCP errors).
  3. idle, prepare: internal.
  4. poll: wait for new I/O events and run their callbacks (most of your app’s work: sockets, files).
  5. check: setImmediate callbacks.
  6. close callbacks: 'close' events such as socket.on('close').

Between every callback (not just between phases, since Node 11), Node drains two queues: first the process.nextTick queue, then the promise microtask queue. The loop exits when nothing is left to wait for (no timers, sockets, handles).

Q10. What is the output order? [M]

// CommonJS file
console.log('A');
setTimeout(() => console.log('F timeout'), 0);
setImmediate(() => console.log('G immediate'));
Promise.resolve().then(() => console.log('D promise'));
queueMicrotask(() => console.log('E microtask'));
process.nextTick(() => console.log('C nextTick'));
console.log('B');

A B C D E, then F and G in an order that is not guaranteed from the main module. A 0 ms timer is really at least 1 ms; whether it has expired when the loop first reaches the timers phase depends on how fast startup was. Inside an I/O callback, setImmediate always runs before setTimeout(0), because the check phase follows the poll phase.

Run examples/event-loop-order.cjs several times and watch the tail change.

Q11. process.nextTick vs setImmediate vs queueMicrotask? [M]

  Runs Use for
process.nextTick(fn) Before promise microtasks, as soon as the current operation completes Emitting events after a constructor returns; Node-internal style. Easy to misuse.
queueMicrotask(fn) / Promise.then After the nextTick queue, before the loop continues Standard, portable “run right after this”
setImmediate(fn) Check phase of the next loop iteration Yield to I/O, break up long work
setTimeout(fn, 0) Timers phase, at least 1 ms later Delays

The names are historically backwards: nextTick runs sooner than setImmediate.

Q12. What is event-loop starvation? [S]

If microtasks or nextTick callbacks keep scheduling more of themselves, the loop never moves to the next phase and I/O stops:

function spin() { process.nextTick(spin); }  // the server stops responding
spin();

Recursive setImmediate does not starve I/O, because each one waits for the next check phase.

Q13. In an ES module, why does a promise callback run before nextTick? [S]

ES module evaluation is itself driven by promises: top-level code runs as part of a microtask. Promise callbacks scheduled there are drained in the same microtask checkpoint, before Node gets to process the nextTick queue. In CommonJS (or inside any regular callback), nextTick runs first. The test test/event-loop.test.mjs demonstrates both. Lesson: do not write code that depends on the relative order of nextTick and promises.

Q14. How do you detect a blocked event loop? [S]

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

Q15. Why can fs calls be slow under load even though they are async? [S]

Async fs work runs on the libuv thread pool, which has 4 threads by default. If many file reads, crypto.pbkdf2 calls or zlib jobs are queued, they wait for a free thread. Options: raise UV_THREADPOOL_SIZE (set before the pool is first used, ideally as an environment variable), reduce sync-ish heavy calls, use streams, or move CPU work to workers. Network sockets do not use the pool.


3. Modules: CommonJS and ES Modules

Q16. CommonJS vs ES modules: what are the differences? [M]

  CommonJS (CJS) ES modules (ESM)
Syntax require(), module.exports import, export
Loading Synchronous, at run time Parsed first, linked, then evaluated (async-capable)
Top-level await No Yes
this at top level module.exports undefined
__dirname, __filename Available Use import.meta.dirname, import.meta.filename
Strict mode Opt-in Always
Exports A mutable object (copied values) Live bindings
File markers .cjs, or .js with no "type" / "type": "commonjs" .mjs, or .js with "type": "module"

Q17. Can CommonJS load an ES module? [M]

ESM can import CJS: import pkg from './x.cjs' gives module.exports as the default export; named imports work when Node can detect them statically.

Q18. exports vs module.exports? [J]

exports is a shortcut variable that initially points to module.exports. require returns module.exports.

exports.a = 1;              // fine: adds to module.exports
exports = { a: 1 };         // broken: rebinds the local variable only
module.exports = { a: 1 };  // fine: replaces the exported object

Q19. How does require caching work? [M]

The first require of a resolved filename runs the file and stores module.exports in require.cache. Later requires return the same object, so modules act like singletons. Clearing require.cache[require.resolve('./x')] forces a reload (rarely a good idea). ESM has its own cache that cannot be cleared; import('./x.mjs?v=2') loads a new instance because the URL differs.

Q20. What happens with circular dependencies? [S]

In CJS, if a requires b and b requires a, then b gets a’s partially filled module.exports (whatever a set before its require('b') line). In ESM, bindings are live, but reading an export before its module finished evaluating throws a ReferenceError (temporal dead zone) for let/const/class. Fix the design: extract shared code into a third module, or import lazily inside functions.

Q21. What does the "exports" field in package.json do? [S]

It defines the public entry points of a package and blocks deep imports of anything not listed. It also supports conditions:

{
  "name": "my-lib",
  "type": "module",
  "exports": {
    ".": { "import": "./dist/index.js", "require": "./dist/index.cjs" },
    "./utils": "./dist/utils.js",
    "./package.json": "./package.json"
  }
}

import 'my-lib/internal/x.js' now fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Adding "exports" to an existing package is a breaking change for anyone using deep imports.

Q22. Why use the node: prefix? [J]

import fs from 'node:fs' makes it explicit that this is a core module and can never be shadowed by an npm package with the same name. Some newer core modules (node:test, node:sqlite, node:sea) are only available with the prefix.

Q23. How does require resolve a path? [M]

For require('x'): core module? Else, if it starts with ./, ../ or /, load the file (trying .js, .json, .node) or directory (package.json "main", then index.js). Otherwise walk up the directories looking in each node_modules/x. ESM resolution is stricter: relative imports need the full file extension, and directory imports are not resolved.


4. Asynchronous Patterns

Q24. What is the error-first callback convention? [J]

Callbacks receive (err, result). Check err first; never throw from inside the callback expecting the caller to catch it.

fs.readFile('a.txt', 'utf8', (err, text) => {
  if (err) return handle(err);
  use(text);
});

Q25. What is callback hell and how do you avoid it? [J]

Deeply nested callbacks that are hard to read and get error handling wrong. Fixes: promises and async/await, small named functions, the promise versions of core APIs (node:fs/promises, node:timers/promises, node:stream/promises, node:dns/promises) and util.promisify for old callback APIs.

Q26. Compare Promise.all, allSettled, race and any. [J]

Method Resolves when Rejects when
Promise.all All fulfil (array of values) The first rejection
Promise.allSettled All settle (array of {status, value/reason}) Never
Promise.race First settles (value) First settles with rejection
Promise.any First fulfils All reject (AggregateError)

Promise.all does not cancel the other promises when one rejects; they keep running. Pass an AbortSignal if you need cancellation.

Q27. Sequential vs parallel await. [J]

// Sequential: total time = a + b
const a = await getUser();
const b = await getOrders();

// Parallel: total time = max(a, b)
const [user, orders] = await Promise.all([getUser(), getOrders()]);

await inside for...of is sequential; array.map(async ...) starts everything at once. For “parallel, but at most N at a time”, see mapWithLimit.

Q28. What happens on an unhandled promise rejection? [M]

Since Node 15 the default mode is throw: an unhandled rejection is raised as an uncaught exception and the process exits with a non-zero code. Change with --unhandled-rejections=warn|strict|none (not recommended). Log and exit through process.on('unhandledRejection', ...) if you need custom reporting. A common cause is a promise created early and awaited later, after it already rejected.

Q29. How do you cancel async work? [M]

With AbortController. Many core APIs accept signal: fetch, fs.readFile, timers/promises, events.once, stream.pipeline, child_process.spawn.

const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
try {
  const res = await fetch('https://example.com', { signal: controller.signal });
} catch (err) {
  if (err.name === 'AbortError') console.log('cancelled');
  else throw err;
}

// Shorthand for a timeout:
await fetch(url, { signal: AbortSignal.timeout(5000) });   // rejects with a TimeoutError
// Combine signals:
AbortSignal.any([userSignal, AbortSignal.timeout(5000)]);

Q30. Implement promisify. [M]

const promisify = (fn) => (...args) =>
  new Promise((resolve, reject) =>
    fn(...args, (err, value) => (err ? reject(err) : resolve(value))));

The real util.promisify also supports a custom util.promisify.custom symbol for functions with unusual callbacks. See examples/concurrency.mjs.

Q31. What is the difference between return await and return in an async function? [S]

Inside try/catch, return await p catches p’s rejection in the local catch; return p does not, the rejection goes straight to the caller. Outside try, they behave the same, and return await gives a slightly better async stack trace.

Q32. How do async iterators help? [M]

for await (const x of source) consumes anything that implements Symbol.asyncIterator: readable streams, events.on(emitter, 'data'), readline interfaces, paginated API helpers written as async generators. It handles backpressure naturally because the next chunk is not pulled until the loop body finishes.

async function* pages(url) {
  while (url) {
    const res = await fetch(url);
    const body = await res.json();
    yield body.items;
    url = body.next;
  }
}
for await (const items of pages('https://api.example.com/items')) process(items);

5. Events and EventEmitter

Q33. What is EventEmitter? [J]

The base class for objects that emit named events (on, once, off, emit). Streams, HTTP servers, sockets and process are all EventEmitters. Listeners run synchronously in registration order when emit is called.

Q34. What is special about the 'error' event? [M]

If an emitter emits 'error' and has no 'error' listener, Node throws the error, usually crashing the process. Always attach 'error' handlers to streams, sockets and child processes. See examples/emitter.mjs for a minimal emitter that copies this rule.

Q35. What is the “MaxListenersExceededWarning”? [M]

Adding more than 10 listeners for one event on one emitter prints a warning, because it often means a leak (adding a listener per request and never removing it). Fix the leak; raise the limit with emitter.setMaxListeners(n) only when many listeners are intended.

Q36. How do you await an event? [M]

import { once, on } from 'node:events';
const [connection] = await once(server, 'connection');
for await (const [msg] of on(socket, 'message')) handle(msg);   // async iterator over events

once rejects if 'error' is emitted first.


6. Buffers and Streams

Q37. What is a Buffer? [J]

A fixed-size chunk of raw bytes (a subclass of Uint8Array) used for binary data: files, sockets, crypto.

const b = Buffer.from('héllo', 'utf8');
b.length;                 // 6 bytes, not 5 characters
b.toString('base64');     // 'aMOpbGxv'
Buffer.alloc(10);         // zero-filled
Buffer.allocUnsafe(10);   // faster, may contain old memory: overwrite it before use
Buffer.concat([b1, b2]);

Q38. What are the four stream types? [J]

Q39. Why use streams? [J]

Constant memory regardless of data size, and processing starts before all data arrives. Reading a 5 GB log with readFile needs 5 GB of RAM (and fails above the max string/buffer size); streaming needs a few KB.

import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';

await pipeline(createReadStream('app.log'), createGzip(), createWriteStream('app.log.gz'));

Q40. What is backpressure? [M]

When the writer is slower than the reader, data piles up in memory. Streams signal this: writable.write(chunk) returns false once the internal buffer exceeds highWaterMark; the producer should pause until the 'drain' event. pipe(), pipeline() and for await handle it for you. Manual on('data') + write() without checking the return value is the classic bug.

async function writeMany(stream, rows) {
  for (const row of rows) {
    if (!stream.write(row)) await once(stream, 'drain');
  }
  stream.end();
}

Q41. pipe() vs pipeline()? [M]

a.pipe(b) does not forward errors or destroy the other streams when one fails, so file handles and sockets can leak. stream.pipeline() (and the promise version in node:stream/promises) propagates errors, destroys every stream on failure and tells you when everything finished. Prefer pipeline in production code.

Q42. What is objectMode and highWaterMark? [M]

By default streams carry Buffers/strings and highWaterMark is a byte count (64 KiB for most streams since Node 22, 16 KiB before). In objectMode, each chunk is any JS value and highWaterMark counts objects (default 16). The line splitter in examples/streams.mjs takes bytes in and emits strings in object mode.

Q43. How do you write a Transform stream? [M]

Implement transform(chunk, encoding, callback) and optionally flush(callback) for data left at the end. The key trap: a chunk boundary can split a line, a multi-byte UTF-8 character or a JSON record. Keep a remainder buffer (see lineSplitter) and use StringDecoder or setEncoding('utf8') for text.

Q44. Node streams vs Web Streams? [S]

Node also implements the WHATWG ReadableStream/WritableStream/TransformStream (globals). fetch returns web streams (res.body). Convert with Readable.fromWeb(webStream) and Readable.toWeb(nodeStream). Node streams are still the native type for fs, net and http.


7. File System and Paths

Q45. Which fs API should you use? [J]

Q46. Why is checking fs.existsSync before opening a file a bug? [M]

Race condition (TOCTOU, time of check to time of use): the file can be deleted or created between the check and the open. Just try the operation and handle ENOENT:

try {
  return JSON.parse(await readFile(path, 'utf8'));
} catch (err) {
  if (err.code === 'ENOENT') return defaults;
  throw err;
}

Q47. path.join vs path.resolve? [J]

join concatenates segments and normalizes (join('a', '../b') gives 'b'). resolve processes segments right to left until it builds an absolute path, using process.cwd() if needed. Use path.resolve(import.meta.dirname, 'data.json') to locate files relative to the module rather than to wherever the user ran the command.

Q48. How do you watch files? [M]

fs.watch (OS events, efficient, details vary by platform, can fire twice per change) or fs.watchFile (polling). For dev servers, node --watch app.js restarts on change without extra tools.


8. HTTP and Networking

Q49. Build a minimal HTTP server without frameworks. [J]

See examples/server.mjs: routing on req.method and URL.pathname, reading the body with for await, a body size limit, JSON errors with the right status codes, and graceful shutdown. The test starts it on port 0 (random free port) and calls it with fetch.

Q50. What does Express middleware do? [J]

A function (req, res, next) in a chain. Each can read or modify req/res, end the response, or call next() to pass on (or next(err) to jump to error handlers, which have four parameters (err, req, res, next)). Order of registration is order of execution. Express 5 also forwards rejected promises from async handlers to the error handler.

Q51. How do you implement graceful shutdown? [M]

On SIGTERM (sent by Kubernetes, Docker, systemd):

  1. Stop accepting new connections: server.close().
  2. Mark the instance unhealthy so the load balancer stops routing to it.
  3. Let in-flight requests finish; close idle keep-alive sockets (server.closeIdleConnections()).
  4. Close DB pools, flush logs and queues.
  5. Exit; force-close after a timeout (server.closeAllConnections()).

Q52. Is fetch built into Node? [J]

Yes. fetch, Request, Response, Headers and FormData are globals (stable since Node 21), implemented by the Undici library. Differences from browsers: no CORS, no cookies jar, and you must consume or cancel the response body to free the connection.

Q53. What is HTTP keep-alive and why does it matter? [M]

Reusing a TCP (and TLS) connection for multiple requests avoids handshakes and cuts latency. Node’s global HTTP agent enables keep-alive by default since Node 19. Server side, server.keepAliveTimeout should be longer than the idle timeout of the load balancer in front, otherwise the server closes sockets the balancer still thinks are open, causing random 502s.

Q54. How do you handle CORS? [J]

CORS is enforced by browsers, not by Node. Your server answers the preflight OPTIONS request and sets Access-Control-Allow-Origin (a specific origin, not *, when credentials are used), -Methods, -Headers. Server-to-server calls ignore CORS entirely.

Q55. How would you handle a large file upload? [M]

Stream it: pipe req to disk or to object storage with pipeline, enforce a size limit while streaming, validate type by content not only by name, and never Buffer.concat the whole body. For multipart forms use a streaming parser (busboy) instead of loading everything into memory. For very large files, use pre-signed URLs so the client uploads directly to storage.

Q56. WebSockets vs Server-Sent Events vs long polling? [M]


9. Processes, Threads and Scaling

Q57. exec vs execFile vs spawn vs fork? [M]

Function Shell Output Use
exec(cmd) Yes Buffered, size-limited (maxBuffer) Quick commands with trusted input only
execFile(file, args) No Buffered Run a program with arguments safely
spawn(cmd, args) No (unless shell: true) Streams Long-running or large output
fork(modulePath) No IPC channel + streams Another Node process you talk to with send()

Never build an exec string from user input: exec('convert ' + filename) is command injection. Use execFile/spawn with an args array.

Q58. Worker threads vs child processes vs cluster? [M]

  worker_threads child_process cluster
Unit Thread in the same process Separate OS process Separate Node processes sharing a port
Memory Separate heaps, can share SharedArrayBuffer Fully separate Fully separate
Communication postMessage, transferable objects stdio, IPC IPC
Best for CPU-heavy JS (parsing, hashing, image work) Running other programs, isolation Using all CPU cores for an HTTP server

In containers, many teams skip cluster and run one Node process per container, scaling with the orchestrator. Example worker: examples/worker-sum.mjs.

Q59. How do worker threads share memory? [S]

By default postMessage copies data with the structured clone algorithm. ArrayBuffers can be transferred (zero-copy, the sender loses access). SharedArrayBuffer is visible to both threads at once; coordinate with Atomics (Atomics.add, Atomics.wait, Atomics.notify) to avoid races. Use a pool (for example Piscina) rather than one worker per task, since starting a worker costs milliseconds and memory.

Q60. How do you scale a Node.js app? [M]

Vertically: use all cores (cluster or several processes), offload CPU work. Horizontally: stateless instances behind a load balancer, sessions and caches in Redis or the database, background jobs in a queue (BullMQ, SQS, RabbitMQ), static assets on a CDN, database connection pooling sized for the number of instances. Measure first; most Node apps are limited by the database, not by Node.


10. Error Handling

Q61. Operational errors vs programmer errors? [M]

Q62. Should you use process.on('uncaughtException') to keep the server alive? [M]

No. After an uncaught exception the process is in an unknown state (half-finished requests, leaked locks). Use the handler only to log synchronously and exit with a non-zero code. Run under a supervisor (Kubernetes, systemd, Docker restart policy, PM2) that restarts it.

Q63. How do you add context to errors? [M]

Use cause (standard since ES2022):

try {
  await db.query(sql);
} catch (err) {
  throw new Error(`Failed to load user ${id}`, { cause: err });
}

Custom error classes help callers branch on type:

class NotFoundError extends Error {
  constructor(resource, options) {
    super(`${resource} not found`, options);
    this.name = 'NotFoundError';
    this.status = 404;
  }
}

Q64. Why does a try/catch not catch this error? [J]

try {
  setTimeout(() => { throw new Error('boom'); }, 0);
} catch (e) { /* never runs */ }

The callback runs later, on a different call stack, after try has finished. Catch inside the callback, or use promises and await so the error flows back to your try.

Q65. What exit codes should a Node process use? [J]

0 success; non-zero failure. Node itself uses 1 for uncaught exceptions and 13 for a top-level await that never settled. Shells report a process killed by a signal as 128 + signal number (130 for SIGINT). Set process.exitCode and let the process end naturally when you can.


11. Performance and Memory

Q66. What are common causes of memory leaks in Node? [M]

Q67. How do you find a memory leak? [S]

  1. Confirm: watch process.memoryUsage().heapUsed or container memory over time under steady load. A sawtooth is normal GC; a rising floor is a leak.
  2. Take heap snapshots: node --inspect + Chrome DevTools Memory tab, --heapsnapshot-signal=SIGUSR2, v8.writeHeapSnapshot(), or --heapsnapshot-near-heap-limit=2.
  3. Compare two snapshots taken minutes apart; sort by retained size; follow the retainers path to your code.

Q68. What does --max-old-space-size do? [M]

Sets the V8 old-generation heap limit in MB (for example --max-old-space-size=2048). In containers, set it below the container memory limit so V8 collects garbage before the kernel’s OOM killer kills the process; recent Node versions also size the default heap from the container’s cgroup limit. It does not limit Buffers, which live outside the V8 heap (external / arrayBuffers in memoryUsage()).

Q69. How do you profile CPU usage? [M]

node --cpu-prof app.js (writes a profile on exit), node --inspect then DevTools Performance tab, node --prof + node --prof-process for V8 tick logs, or flame graphs with tools like 0x or Clinic.js. Look for the widest bars: synchronous JSON work, regex, sync crypto, logging.

Q70. How can you speed up JSON-heavy endpoints? [S]

Return less data (pagination, field selection), cache serialized responses, stream large arrays instead of one JSON.stringify, use schema-based serializers (Fastify’s fast-json-stringify), move huge parses to worker threads, and compress at the proxy. Measure before and after.

Q71. What does structuredClone do and when is it better than JSON.parse(JSON.stringify(x))? [J]

Deep copies values with the structured clone algorithm: supports Date, Map, Set, RegExp, typed arrays, circular references, and undefined inside objects. JSON round-tripping loses all of those. Neither copies functions or class prototypes.


12. Security

Q72. What are the top security risks in Node apps? [M]

Injection (SQL, NoSQL, command, template), broken authentication, secrets in code, vulnerable dependencies, prototype pollution, ReDoS, path traversal, SSRF, missing rate limiting, verbose error messages in production, and unsafe deserialization. The OWASP Node.js Security Cheat Sheet is a good checklist.

Q73. What is prototype pollution? [S]

Attacker-controlled keys like __proto__ or constructor.prototype reach a recursive merge or a set(obj, path, value) helper, modifying Object.prototype for the entire process:

const payload = JSON.parse('{"__proto__": {"isAdmin": true}}');
deepMerge({}, payload);   // naive merge
({}).isAdmin;             // true for every object

Defend: block __proto__, constructor, prototype keys, use Object.create(null) or Map for user-keyed data, validate input with a schema, and keep merge libraries updated. Node also has --disable-proto=delete.

Q74. What is ReDoS? [S]

Regular Expression Denial of Service: a regex with nested quantifiers like /^(a+)+$/ takes exponential time on crafted input, blocking the event loop (and thus every user). Avoid nested quantifiers, limit input length before matching, and lint regexes.

Q75. How do you prevent path traversal? [M]

import path from 'node:path';
const ROOT = path.resolve('public');
function safePath(userPath) {
  const full = path.resolve(ROOT, userPath);
  if (full !== ROOT && !full.startsWith(ROOT + path.sep)) throw new Error('Forbidden');
  return full;
}

Without this check, GET /files/../../etc/passwd escapes the folder.

Q76. How do you manage secrets? [J]

Environment variables or a secret manager, never committed files. Locally, node --env-file=.env app.js loads a .env file without the dotenv package (available since Node 20.6; --env-file-if-exists for optional files). Validate required variables at startup and fail fast. Do not log process.env.

Q77. What is the Node.js permission model? [S]

Running with --permission restricts what the process can access; you allow specific things with --allow-fs-read=..., --allow-fs-write=..., --allow-child-process, --allow-worker and so on. It is a safety net against surprising behaviour by dependencies, not a sandbox for hostile code. It became stable in the Node 22/23 timeframe; check node --help on your version for the exact flags.

Q78. How do you reduce supply-chain risk from npm? [M]

Commit the lockfile and use npm ci in CI. Review new dependencies (maintenance, downloads, install scripts). Run npm audit and enable automated update PRs. Consider --ignore-scripts where possible. Pin GitHub Actions and Docker base images. Prefer fewer, well-maintained packages; Node’s standard library now covers testing, fetch, env files, watch mode and parsing CLI args (util.parseArgs).


13. Testing and Tooling

Q79. How do you test without Jest or Mocha? [J]

With the built-in runner node:test and node:assert:

import { test, describe, mock } from 'node:test';
import assert from 'node:assert/strict';

describe('sum', () => {
  test('adds numbers', () => assert.equal(1 + 2, 3));
  test('async works', async () => assert.deepEqual(await Promise.resolve([1]), [1]));
});

Run node --test. It finds *.test.{js,mjs,cjs} and files in test/ folders, supports --watch, --test-only, --test-name-pattern, coverage (--experimental-test-coverage), mocks and fake timers. This repo’s tests use it.

Q80. How do you mock timers and functions? [M]

test('debounce', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  const fn = t.mock.fn();
  const d = debounce(fn, 100);
  d(); d();
  t.mock.timers.tick(100);
  assert.equal(fn.mock.callCount(), 1);
});

See test/misc.test.mjs.

Q81. How do you test an HTTP server? [M]

Start it on port 0, read the real port from server.address().port, call it with fetch, close it at the end. No test framework plugins needed. See test/server.test.mjs. For unit tests, keep handlers as plain functions and test them without a socket.

Q82. Can Node run TypeScript directly? [M]

Yes for most code: current Node versions strip TypeScript type annotations and run .ts files (node app.ts), enabled by default since 23.6 and 22.18. It only removes types; it does not type-check (run tsc --noEmit for that) and does not support TS features that need code generation, such as enum and namespace, unless you enable --experimental-transform-types. Imports must use the .ts extension.

Q83. Which useful CLI flags should you know? [M]

Flag Purpose
--watch Restart on file changes
--env-file=.env Load environment variables
--inspect / --inspect-brk Attach DevTools / VS Code debugger
--test Run tests
--cpu-prof, --heap-prof Write profiles
--max-old-space-size=N Heap limit in MB
--enable-source-maps Stack traces point to TS/original sources
--trace-warnings Stack trace for warnings such as deprecations
--permission Enable the permission model
--run <script> Run a package.json script without npm overhead

Q84. How do you parse CLI arguments without a library? [J]

import { parseArgs } from 'node:util';
const { values, positionals } = parseArgs({
  options: { verbose: { type: 'boolean', short: 'v' }, out: { type: 'string' } },
  allowPositionals: true,
});

14. npm and Package Management

Q85. dependencies vs devDependencies vs peerDependencies? [J]

Q86. What do ^ and ~ mean in versions? [J]

Semantic versioning MAJOR.MINOR.PATCH. ^1.4.2 allows >=1.4.2 <2.0.0; ~1.4.2 allows >=1.4.2 <1.5.0; 1.4.2 is exact. For 0.x, ^0.4.2 means <0.5.0, because pre-1.0 minor bumps may break.

Q87. Why commit package-lock.json, and what does npm ci do? [J]

The lockfile records the exact resolved version and integrity hash of every package in the tree, so every machine installs the same thing. npm ci installs exactly from the lockfile, deletes node_modules first, and fails if package.json and the lockfile disagree. Use npm install to change dependencies, npm ci in CI and Docker builds.

Q88. What is npx? [J]

Runs a package’s binary: from local node_modules/.bin if present, otherwise downloads it temporarily. npx create-vite@latest scaffolds without a global install. Treat it like running any downloaded code.

Q89. npm vs pnpm vs Yarn? [M]

All read package.json. pnpm uses a content-addressed store and symlinks, saving disk and preventing access to undeclared dependencies. Yarn (Berry) offers Plug’n’Play. npm ships with Node. Corepack, the tool that pinned pnpm/Yarn versions via the packageManager field, is no longer bundled with Node.js 25 and later; install it with npm install -g corepack if a project relies on it.

Q90. What are npm lifecycle scripts and why are they a risk? [M]

preinstall, install, postinstall run automatically during npm install, including for dependencies, so a compromised package can execute code on your machine or CI. Run npm install --ignore-scripts when you can, and audit packages that need scripts (native addons legitimately do).


15. Node.js Versions and Releases

Q91. How do Node.js releases and LTS work? [J]

Historically: a new major every April and October; even-numbered majors become LTS (long-term support) in October, getting about 30 months of support in total; odd majors are short-lived. Production apps should run an LTS line. Node 26 (released spring 2026) is the last release on that schedule; from Node 27 the project moves to one major release per year (April), each promoted to LTS in October. Always check nodejs.org/en/about/previous-releases.

Q92. How do you manage several Node versions? [J]

A version manager: nvm, fnm, Volta, or mise. Pin the version per project with .nvmrc / .node-version and "engines": { "node": ">=22" } in package.json, and use the same major in CI, Docker and production.

Q93. Name recent additions you would use in new code. [M]


16. Coding Exercises

Each has a solution in examples/ and tests in test/. Try them before reading the code.

# Exercise Solution Concepts
E1 Predict the event loop output event-loop-order.cjs phases, microtasks
E2 Run async tasks with a concurrency limit, keeping order concurrency.mjs mapWithLimit promise pool
E3 Retry with exponential backoff concurrency.mjs retry error handling, timers
E4 Add a timeout to any promise concurrency.mjs withTimeout Promise.race, cleanup
E5 Memoize an async function, deduplicating in-flight calls concurrency.mjs memoizeAsync caching promises
E6 Implement promisify concurrency.mjs promisify callbacks to promises
E7 Debounce and throttle timing.mjs closures, timers
E8 Write a tiny EventEmitter with once and 'error' rule emitter.mjs events
E9 Count matching lines in a huge file in constant memory streams.mjs Transform, pipeline
E10 LRU cache with O(1) get/set lru-cache.mjs Map ordering
E11 Token bucket rate limiter rate-limiter.mjs algorithms, time injection
E12 HTTP JSON server with body limit and graceful shutdown server.mjs http, signals
E13 Move CPU work to a worker thread worker-sum.mjs worker_threads

Follow-up questions interviewers ask on these:


17. Scenario and Design Questions

Q94. Your API’s p99 latency spikes every few minutes. How do you investigate? [S]

Check whether all routes spike together (event loop blocked or GC pauses) or only some (a slow dependency). Add event-loop delay metrics, correlate with GC logs (--trace-gc) and CPU, look for periodic jobs (cache rebuilds, cron tasks, big JSON.stringify of metrics), take a CPU profile during a spike. Typical fixes: move the periodic job to a worker or another service, stream instead of buffer, add pagination.

Q95. Design a job queue for sending 1 million emails. [S]

Producer writes jobs to a durable queue (Redis with BullMQ, SQS, RabbitMQ). Workers consume with a concurrency limit per worker, respect the provider’s rate limit (token bucket), retry with backoff on transient errors, send permanent failures to a dead-letter queue, and use an idempotency key per email so a retry never double-sends. Track progress in the database; make workers stateless so you can scale them.

Q96. How do you handle 10,000 concurrent WebSocket connections? [S]

One Node process can hold many idle sockets; memory per connection is the limit. Keep per-connection state small, use heartbeats (ping/pong) to drop dead connections, raise file descriptor limits (ulimit -n), run several processes behind a load balancer with sticky sessions (or no session affinity if state is external), and use Redis pub/sub or a broker to broadcast across instances.

Q97. How do you make a deployment zero-downtime? [M]

Rolling deploys with readiness checks; graceful shutdown on SIGTERM (Q51); backward-compatible database migrations (expand, migrate, contract); health endpoints that check real dependencies; and a preStop delay in Kubernetes so the endpoint is removed from the load balancer before the process stops accepting connections.

Q98. How would you structure a medium-size Node.js service? [M]

By feature (users, orders, billing), each with routes/controllers, a service layer with business logic, and a data-access layer. Configuration loaded and validated once at startup. Dependencies passed in (simple function parameters or a small container) so they are easy to replace in tests. Centralized error handling and logging (structured JSON logs with a request ID). Keep framework code at the edges so business logic is plain, testable functions.

Q99. How do you log properly in production? [M]

Structured JSON logs (pino is fast), one line per event, with level, timestamp, request ID, user/tenant ID where allowed. Do not log secrets or full request bodies. Write to stdout and let the platform ship logs. Use log levels and sampling to control volume. Trace across services with OpenTelemetry.

Q100. What would you check in a Node.js code review? [S]

Unhandled promises and missing await; sync calls in hot paths; unbounded caches, arrays and concurrency (Promise.all over 50,000 items); missing timeouts on outgoing calls; stream errors not handled; user input reaching exec, SQL, file paths or regexes; secrets in logs; missing input validation; tests for failure paths, not just the happy path.


Quick Revision Sheet

Topic One-liner
Event loop phases timers, pending, idle/prepare, poll, check, close
Microtask order nextTick queue, then promise queue, between every callback
Thread pool 4 threads default: fs, dns.lookup, some crypto, zlib
CJS vs ESM require sync vs import async-capable; .cjs/.mjs/"type"
Streams Readable, Writable, Duplex, Transform; use pipeline
Backpressure write() returns false, wait for 'drain'
Unhandled rejection Crashes the process by default (since Node 15)
'error' events Unhandled ones throw
Scale CPU worker_threads; scale cores: cluster or more processes
Shutdown SIGTERM, server.close(), drain, close pools, exit
Secrets env vars, --env-file, never commit
Tests node --test, node:assert/strict, t.mock.timers
Lockfile commit it, npm ci in CI

Node.js vs Deno vs Bun

Interviewers increasingly ask how Node compares with the newer runtimes.

  Node.js Deno Bun
Engine V8 V8 JavaScriptCore
Written in C++ (libuv) Rust (Tokio) Zig
TypeScript Type stripping built in (no type check) Built in, with deno check Built in (transpiles)
Package manager npm (pnpm, Yarn separately) deno add, npm and JSR packages bun install (fast, npm-compatible)
Security model Opt-in permission model Permissions required by default Full access
Test runner node:test deno test bun test
npm compatibility Native High (npm: specifiers) High
Best for Production default, biggest ecosystem Secure scripts, edge functions Fast tooling, scripts, dev servers

A good answer: “Node is the stable default with the largest ecosystem and LTS releases; Deno and Bun pushed Node to add built-in TypeScript, test runner, watch mode and a permission model.”

FAQ

Which Node.js version should I learn for interviews? The current Active LTS line, and mention what changed recently (built-in test runner, fetch, type stripping, require(esm)). Version questions are about awareness, not memorized numbers.

Do I need Express for Node interviews? Know it at the middleware level (Q50), but strong answers about the event loop, streams and error handling matter more than any framework.

How should I practice the coding exercises? Implement each from scratch in 15 minutes without looking, then compare with examples/ and run npm test against your version.

What are the most common senior-level Node questions? Event loop internals and starvation, memory leak investigation, backpressure, graceful shutdown, scaling with workers or processes, and supply-chain security.

Is TypeScript expected in Node interviews? Often. Be ready to explain how you run it (type stripping, tsx, or a build step) and that types are erased at run time, so input still needs validation.

Where to Go Next

  1. Read the official Node.js Learn guides, especially the event loop and streams sections.
  2. Skim the Node.js API docs for stream, events, worker_threads and test.
  3. Study the Node.js Best Practices list for production patterns.
  4. Rebuild one exercise per day in examples/ from memory and keep npm test green.
  5. Build a small API with graceful shutdown, structured logging and tests, and talk through it in your interview.

Contributing

PRs welcome. Keep entries accurate and version-aware: if an answer depends on a Node.js version, say which. New coding exercises need a solution in examples/ and a test in test/, and npm test must pass with no dependencies.

License

MIT. See LICENSE.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.