Node.js
The JavaScript runtime behind most server-side JS: one event loop, libuv underneath, core modules for files, sockets and processes. Interviewers probe what Node does while your callback waits.
on this pageshowhide
explore
- Scheduling Model20 questions
- Phase Order and Threadpool5 questions
- Tick Queue Priority5 questions
- Timers and Immediates5 questions
- Blocking and Lag Measurement5 questions
- Module Formats and Loading19 questions
- CommonJS at Runtime4 questions
- ESM Adoption and Interop5 questions
- Specifier Resolution and Exports5 questions
- Loader Hooks and TypeScript5 questions
- Streams and Byte Buffers21 questions
- Classes and Reading Modes6 questions
- Backpressure and Pipelines5 questions
- Implementing Custom Transforms5 questions
- Binary Data Handling5 questions
- Filesystem and Network I/O24 questions
- Async File Operations6 questions
- HTTP and HTTP/2 Servers6 questions
- Calling HTTP Services6 questions
- TCP, UDP, and DNS6 questions
- Multi-Core Execution20 questions
- Worker Threads5 questions
- Spawning Subprocesses6 questions
- Cluster Module4 questions
- Choosing a Parallelism Model5 questions
- Reliability and Diagnostics27 questions
- Error Conventions and Propagation5 questions
- Process Crash Policy6 questions
- Draining Before Exit5 questions
- Request Context and Debugging6 questions
- Heap Limits and Leaks5 questions
- Bundled Tooling12 questions
- Dependency-Free Testing6 questions
- Environment and Runtime Flags6 questions
questions
143 · 7 sectionsIn a Node.js server, why do fs.readFileSync and crypto.pbkdf2Sync in a request handler stall every other client, while fs.readFile and crypto.pbkdf2 do not?
basics
~20 sNode runs every request handler on one main thread. A Sync call does its read or hashing inside the current callback, so no other client is served until it returns; the async versions hand the work to libuv's threadpool.
Node.js is called single-threaded, yet a slow file read does not stall other requests; which threads does a Node process actually use?
basics
~20 sAll JavaScript runs on one main thread that drives the event loop. Socket I/O is watched by the kernel from that thread, while async fs calls, dns.lookup(), zlib and some crypto run on libuv's threadpool, four threads by default.
In a CommonJS Node.js script, in what order do process.nextTick, resolved-promise .then and setTimeout(0) callbacks run, and why?
basics
~20 sSynchronous code first, then every process.nextTick callback, then every promise callback, then the timeout. Node drains its own next tick queue before V8's microtask queue after each operation; setTimeout waits for the loop's timers phase.
In Node.js, what are the phases of one libuv event loop iteration, in order, and what kind of callback runs in each?
basics
~10 sEach Node.js loop iteration runs timers (due setTimeout and setInterval callbacks), pending callbacks (deferred I/O errors), idle and prepare (internal), poll (new I/O events, where the loop waits), check (setImmediate callbacks), then close callbacks.
In Node.js, which core APIs run on libuv's threadpool rather than kernel I/O notification, and why do crypto.pbkdf2() and socket reads scale differently?
basics
~20 sAsync fs calls, dns.lookup(), async zlib and crypto such as crypto.pbkdf2() and crypto.scrypt() run on libuv's threadpool, four threads by default, so only four proceed at once. Socket reads use kernel readiness notification and need no pool thread.
In Node.js, three files require the same config module and one of them changes a property on it; why do the other two see the change?
basics
~10 sNode runs a CommonJS module once, caches it in require.cache under its resolved filename, and returns the same module.exports object to every later require of that file, so all callers share one mutable instance.
In Node.js 24, how does Node decide whether a given .js file runs as an ES module or as CommonJS?
basics
~20 sAn .mjs file is always an ES module and a .cjs file always CommonJS. A .js file follows the nearest package.json "type" field; without one, Node 24 tries CommonJS and reparses as ESM if it finds module syntax.
In Node.js, how does `require()` turn a bare specifier such as `'some-package'` into a file on disk, and where does it look?
basics
~20 sBuilt-in names win first. Otherwise Node checks the node_modules folder beside the calling file, then each parent's, up to the filesystem root, then NODE_PATH and global folders. In the package found, exports beats main; without exports, extensions and index files are probed.
Moving a Node.js 24 file from CommonJS to ESM, which CommonJS module-scope bindings disappear, and what does Node offer in place of each?
basics
~10 sIn an ES module, require, module, exports, __filename and __dirname do not exist. Node 24 replaces them with import and export, import.meta.filename and import.meta.dirname, import.meta.resolve(), and module.createRequire(import.meta.url) when a real require is still needed.
In Node.js, why does `import './utils'` fail in an ES module when `require('./utils')` finds `utils.js` from CommonJS?
basics
~10 sNode's ES module resolver resolves relative specifiers as URLs and never adds extensions or looks for index files, so './utils' must be written './utils.js'. A missing file throws ERR_MODULE_NOT_FOUND; a folder throws ERR_UNSUPPORTED_DIR_IMPORT.
In Node.js, how do Buffer.from(string, encoding) and buf.toString(encoding) convert between text and bytes, and why can a string's length differ from Buffer.byteLength()?
basics
~20 sBuffer.from(str, enc) encodes a string into bytes and buf.toString(enc) decodes bytes back, both defaulting to utf8; base64 and hex render bytes as text. A string's length counts UTF-16 code units, while Buffer.byteLength() counts encoded bytes.
In a Node.js HTTP server, why stream a large CSV export to the response rather than build it in memory first?
basics
~20 sBuilding the whole export holds every row in memory for each request and sends nothing until the end. Streaming it through stream.pipeline sends rows as they are made and pauses the generator when the client reads slowly, so memory stays bounded.
In Node.js's node:stream module, what are the four fundamental stream classes, and how does a Transform differ from a plain Duplex?
basics
~20 sReadable is a source, Writable a destination, Duplex is both with two independent sides (a TCP socket), and Transform is a Duplex whose output is computed from what was written to it (gzip, a cipher).
Why did stream.pipeline replace readable.pipe() as the way to chain Node.js streams, such as a gzip stage feeding an HTTP response?
basics
~20 sreadable.pipe() handles backpressure but not failure: errors are not forwarded along the chain and the other streams are not closed, so they leak. stream.pipeline forwards the first error, destroys every stream, and reports completion once.
In Node.js, what does writable.write() returning false mean, and what must the code writing to that stream do next?
basics
~20 sfalse means the stream's internal buffer has reached its highWaterMark after accepting the chunk. Nothing is lost, but the writer should stop calling write() and resume on the 'drain' event, or memory grows without limit.
In Node.js, how do you choose between the node:fs/promises, callback and Sync forms of a file operation, and when is a Sync call acceptable?
basics
~20 sNode's fs offers its file operations in promise, callback and Sync forms. Default to node:fs/promises with await, keep callbacks for measured hot paths, and confine Sync calls to startup code and CLIs, because they block the event loop.
In a Node.js http.createServer handler, what are the req and res objects, and how do you read a JSON request body without a framework?
basics
~10 sreq is an http.IncomingMessage: parsed headers plus a Readable stream of body bytes. res is an http.ServerResponse, a Writable. You collect the body chunks yourself, parse them, and must call res.end().
In Node.js, what do http.Agent's keepAlive and maxSockets options control, and what does http.globalAgent use by default?
basics
~20 skeepAlive decides whether an http.Agent pools idle sockets for reuse; maxSockets caps concurrent sockets per origin and queues the rest. new http.Agent() defaults to keepAlive false and maxSockets Infinity; http.globalAgent enables keep-alive with a 5-second timeout.
In Node.js 24, how does the global fetch() differ from http.request() in its implementation, connection pooling and configuration?
basics
~20 sNode 24's global fetch() runs on the bundled undici client, not on node:http, so it pools connections in undici's global dispatcher and ignores http.Agent and http.globalAgent; http.request() is the lower-level, stream-based client those agents configure.
In Node.js node:http, how do res.setHeader and res.writeHead differ, and what causes the ERR_HTTP_HEADERS_SENT error?
basics
~20 sres.setHeader stages one header that Node sends with the first write; res.writeHead sends the status and headers at once and wins over staged ones. Once headers are rendered, any further setHeader or writeHead throws ERR_HTTP_HEADERS_SENT.
What does Node's cluster module do, and how does one entry script know whether it is running as the primary or a worker?
basics
~20 sNode's cluster module runs one script as a primary that calls cluster.fork() and as worker processes that share its server ports. cluster.isPrimary, derived from an environment variable the primary sets for each worker, tells the script which role it has.
In Node.js, which kinds of work belong in worker_threads, and why do I/O-bound endpoints gain little from moving there?
basics
~20 sWorker threads suit CPU-bound JavaScript, such as a long PDF layout or a heavy calculation, that would otherwise freeze the event loop. I/O-bound work already waits outside the JavaScript thread, so a worker adds startup and copying cost without adding throughput.
In Node.js's node:child_process module, how do spawn, exec, execFile and fork differ in shell use, output handling and communication?
basics
~20 sspawn starts a program without a shell and streams its stdio; exec runs a command string through a shell and buffers the output; execFile buffers too but skips the shell; fork starts a Node.js module with an IPC channel.
In Node.js, how do worker_threads, child_process.fork() and the cluster module compare on memory, messaging cost and crash isolation?
basics
~20 sworker_threads run inside one process: cheaper messaging and shareable memory, but a native crash or process-wide out-of-memory kills them all. fork() and cluster start full processes: more memory and JSON IPC by default, but a crash ends only that process.
In Node.js, what does worker.postMessage() do with the value you pass, and how does a transferList change the cost of sending an ArrayBuffer?
basics
~20 spostMessage() copies the value with the structured clone algorithm, paid by both threads. Listing an ArrayBuffer in transferList moves its memory instead: no copy, but the sender's views become unusable. Pooled Buffers cannot be transferred and are cloned with their whole pool.
In Node.js, how does the error-first callback convention work, and what rules must a callback-style API and its caller follow?
basics
~20 sA Node.js callback API calls its last argument as callback(err, result): err is an Error on failure and null on success. The caller checks err first and returns; the API calls back exactly once, always asynchronously.
In Node.js, what does registering process.on('uncaughtException') change about a crash, and why is it unsafe to keep serving afterwards?
basics
~20 sA process 'uncaughtException' listener replaces Node's default of printing the stack trace and exiting with code 1, so the process keeps running. Its state is now unknown, so the handler should log synchronously, clean up and exit non-zero.
In a Node.js HTTP service, how does `AsyncLocalStorage` keep a request id available to every log line and to an error thrown several awaits deep?
basics
~10 sWrap each request in asyncLocalStorage.run(store, handler). Timers, I/O callbacks and awaits started inside inherit that store, so logging and error code read it with getStore() instead of passing the id through every call.
In a Node.js service, what separates an operational error from a programmer error, and which one calls for a retry, a client-error response, or a crash?
basics
~20 sIn Node.js, an operational error is a failure correct code must expect, such as ENOENT or ECONNRESET; a programmer error is a bug, such as ERR_INVALID_ARG_TYPE. Retry transient operational errors, report permanent ones, and never retry bugs.
In Node.js, what does a system error such as ENOENT or ECONNRESET carry, and why should code branch on error.code rather than error.message?
basics
~20 sA Node.js system error is a plain Error with a string code such as ENOENT, a negative platform-specific errno, the failing syscall, and a path or address when relevant. Node documents code as stable; message text may change in any release.
In Node.js, what type does every value in process.env have, and why does a check like if (process.env.CACHE_ENABLED) misfire?
basics
~10 sEvery process.env value is a string, or undefined when the variable is unset. CACHE_ENABLED=false yields the non-empty string 'false', which is truthy, so the branch runs; parse and compare values explicitly.
In Node.js 24, which files does `node --test` run when given no file arguments, and how does it decide that each file passed?
basics
~20 sWith no arguments, node --test runs every file outside node_modules named like *.test.js, _test.js or test-.js, or sitting in a test/ folder (plus .ts forms in Node 24), each in its own child process; a file passes when that process exits 0.
In Node.js 24, what does node --env-file=.env do, and which value wins when the shell environment and several env files set the same variable?
basics
~20 snode --env-file=.env reads the file before your code runs and adds its variables to process.env. A variable already set in the real environment wins over the file, and a later --env-file wins over an earlier one.
What does setting NODE_ENV=production change in the Node.js runtime itself, and why do Node services still set it?
basics
~20 sNothing in Node itself: the runtime does not read NODE_ENV. It is a convention that libraries and frameworks read, for example to enable a template cache, so services set it for their dependencies rather than for Node.
In Node.js `node:test`, how do `mock.fn()` and `mock.method()` record calls, and when does the original behaviour come back?
basics
~20 sBoth return a Proxy whose .mock property records every call's arguments, result, error and this; mocks made through the test context's t.mock are restored when the test ends, while the top-level mock keeps its mocks until mock.reset() or mock.restoreAll().