skip to content

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 pageshow

explore

questions

143 · 7 sections

In 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?

level: juniorimportance: must knowfreq 75%
basics
~20 s

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

open as a page

Node.js is called single-threaded, yet a slow file read does not stall other requests; which threads does a Node process actually use?

level: juniorimportance: must knowfreq 75%
basics
~20 s

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

open as a page

In a CommonJS Node.js script, in what order do process.nextTick, resolved-promise .then and setTimeout(0) callbacks run, and why?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In Node.js, what are the phases of one libuv event loop iteration, in order, and what kind of callback runs in each?

level: middleimportance: must knowfreq 78%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 65%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In Node.js 24, how does Node decide whether a given .js file runs as an ES module or as CommonJS?

level: juniorimportance: must knowfreq 64%
basics
~20 s

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

open as a page

In Node.js, how does `require()` turn a bare specifier such as `'some-package'` into a file on disk, and where does it look?

level: juniorimportance: must knowfreq 58%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 58%
basics
~10 s

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

open as a page

In Node.js, why does `import './utils'` fail in an ES module when `require('./utils')` finds `utils.js` from CommonJS?

level: middleimportance: must knowfreq 55%
basics
~10 s

Node'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.

open as a page

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()?

level: juniorimportance: must knowfreq 60%
basics
~20 s

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

open as a page

In a Node.js HTTP server, why stream a large CSV export to the response rather than build it in memory first?

level: juniorimportance: must knowfreq 65%
basics
~20 s

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

open as a page

In Node.js's node:stream module, what are the four fundamental stream classes, and how does a Transform differ from a plain Duplex?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Readable 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).

open as a page

Why did stream.pipeline replace readable.pipe() as the way to chain Node.js streams, such as a gzip stage feeding an HTTP response?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In Node.js, what does writable.write() returning false mean, and what must the code writing to that stream do next?

level: middleimportance: must knowfreq 75%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 68%
basics
~20 s

Node'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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

req 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().

open as a page

In Node.js, what do http.Agent's keepAlive and maxSockets options control, and what does http.globalAgent use by default?

level: middleimportance: must knowfreq 60%
basics
~20 s

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

open as a page

In Node.js 24, how does the global fetch() differ from http.request() in its implementation, connection pooling and configuration?

level: middleimportance: must knowfreq 65%
basics
~20 s

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

open as a page

In Node.js node:http, how do res.setHeader and res.writeHead differ, and what causes the ERR_HTTP_HEADERS_SENT error?

level: middleimportance: must knowfreq 64%
basics
~20 s

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

open as a page

What does Node's cluster module do, and how does one entry script know whether it is running as the primary or a worker?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Node'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.

open as a page

In Node.js, which kinds of work belong in worker_threads, and why do I/O-bound endpoints gain little from moving there?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

In Node.js's node:child_process module, how do spawn, exec, execFile and fork differ in shell use, output handling and communication?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In Node.js, how do worker_threads, child_process.fork() and the cluster module compare on memory, messaging cost and crash isolation?

level: middleimportance: must knowfreq 75%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 62%
basics
~20 s

postMessage() 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.

open as a page

In Node.js, how does the error-first callback convention work, and what rules must a callback-style API and its caller follow?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In Node.js, what does registering process.on('uncaughtException') change about a crash, and why is it unsafe to keep serving afterwards?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 62%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 60%
basics
~20 s

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

open as a page

In Node.js, what type does every value in process.env have, and why does a check like if (process.env.CACHE_ENABLED) misfire?

level: juniorimportance: must knowfreq 55%
basics
~10 s

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

open as a page

In Node.js 24, which files does `node --test` run when given no file arguments, and how does it decide that each file passed?

level: juniorimportance: should knowfreq 30%
basics
~20 s

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

open as a page

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?

level: middleimportance: should knowfreq 35%
basics
~20 s

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

open as a page

What does setting NODE_ENV=production change in the Node.js runtime itself, and why do Node services still set it?

level: middleimportance: should knowfreq 50%
basics
~20 s

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

open as a page

In Node.js `node:test`, how do `mock.fn()` and `mock.method()` record calls, and when does the original behaviour come back?

level: middleimportance: should knowfreq 28%
basics
~20 s

Both 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().

open as a page