Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Interview questions with answers

Node.js interview questions and answers

Event loop, streams, worker threads, modules and production practice. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.

Subjective
30
Objective
30

Subjective questions 30

1How does Node.js handle many connections on a single thread?Asked almost every time

Node runs JavaScript on one main thread with an event loop. I/O (network, files, DNS) is non-blocking: Node hands it to the operating system or libuv's thread pool and continues; when the work completes, a callback or promise resolution is queued and run on the main thread. So one process can juggle thousands of connections, as long as no code blocks the loop with heavy CPU work.

2Explain the phases of the Node.js event loop.Asked almost every time

Each loop iteration runs phases in order: timers (setTimeout/setInterval callbacks that are due), pending callbacks, poll (waits for and runs I/O callbacks), check (setImmediate), and close callbacks. Between each callback, Node drains process.nextTick callbacks first and then promise microtasks.

3How do you handle CPU-intensive work in Node?Asked almost every time

Move it off the main thread: worker_threads for parallel JavaScript with shared memory or message passing, child processes for separate programs, a job queue with separate worker services for background jobs, or native addons. Running it on the main thread blocks every other request.

4What are streams and why use them?Asked almost every time

Streams process data in chunks instead of loading it all into memory: Readable, Writable, Duplex and Transform streams. They handle large files and network data with constant memory and support backpressure, slowing the producer when the consumer is behind. Use stream.pipeline (or its promise version) to connect them with proper error handling and clean-up.

5How do you build a graceful shutdown in Node.js?Asked almost every time

Listen for SIGTERM and SIGINT, stop accepting new connections (server.close()), finish in-flight requests with a timeout, close database pools and queues, flush logs, then exit. Container platforms send SIGTERM before killing, so this prevents dropped requests.

6How do you structure a production Node.js API?Asked almost every time

Layers: routes or controllers for HTTP, services for business logic, repositories for data access; centralised config and validation; structured logging with request IDs; error-handling middleware; health checks; and tests at each layer. Keep the app separate from listen for testing.

7What is the difference between blocking and non-blocking code in Node?Asked almost every time

Blocking code (synchronous file reads, heavy loops, JSON.parse of huge payloads) stops the event loop, so no other request is served. Non-blocking APIs start work and call back later. Use async APIs and move CPU work to workers to keep latency low.

8process.nextTick vs. setImmediate vs. setTimeout(fn, 0)?Very often asked

nextTick callbacks run right after the current operation, before promise microtasks and before the loop continues; overusing it can starve I/O. setImmediate runs in the check phase after I/O polling. setTimeout(fn, 0) runs in the timers phase at least about 1 ms later. Inside an I/O callback, setImmediate always runs before a zero timeout.

9CommonJS vs. ES modules in Node?Very often asked

CommonJS uses require and module.exports, loads synchronously and is the historic default. ES modules use import/export, are static, support top-level await and are the standard. Use "type": "module" or .mjs for ESM. Modern Node can also require() synchronous ES modules.

10How do you handle errors in Node applications?Very often asked

Use try/catch with async/await, reject promises with Error objects, handle stream and event emitter error events, and use central error middleware in web frameworks. Treat uncaughtException and unhandledRejection as fatal: log, then exit and let a process manager restart, because the process may be in a bad state.

11How do you scale a Node.js service?Very often asked

Run several processes to use all CPU cores (the cluster module, PM2, or more containers), keep services stateless with sessions and caches in Redis, put a load balancer in front, offload heavy work to queues and workers, and cache aggressively. Profile before optimising.

12What is backpressure?Very often asked

When a writable destination cannot keep up, write() returns false; a well-behaved producer pauses until the drain event. pipe and pipeline handle this automatically. Ignoring it makes memory grow until the process crashes.

13How do you find a memory leak?Very often asked

Watch heap usage over time, take heap snapshots with --inspect and Chrome DevTools (or heapdump) and compare them, and look for growing arrays, maps, caches without limits, listeners never removed, or closures holding large objects. --max-old-space-size only delays the crash.

14What is AsyncLocalStorage?Very often asked

A way to keep context (request ID, user, transaction) across asynchronous calls without passing it through every function. Logging and tracing libraries use it to tag logs with the current request.

15How do you measure event loop health?Very often asked

Track event loop delay or utilisation with perf_hooks.monitorEventLoopDelay or performance.eventLoopUtilization(), and alert when lag grows, which signals blocking code or overload.

16How do you manage configuration and secrets?Very often asked

Read configuration from environment variables (with --env-file locally), validate it at startup with a schema, fail fast if something is missing, and fetch secrets from a secrets manager in production rather than committing .env files.

17What are Buffers?Very often asked

Fixed-size chunks of raw binary memory outside the V8 heap, used for files, network data and binary protocols. Convert with buffer.toString('utf8') and Buffer.from(string); streams usually deliver data as Buffers.

18How do child processes work?Very often asked

child_process.spawn runs a command with streamed output, exec buffers output (beware large output and shell injection), execFile avoids a shell, and fork starts another Node process with an IPC channel.

19How do you profile CPU usage in Node?Very often asked

Use node --cpu-prof or --inspect with Chrome DevTools to record a profile, clinic.js flame graphs, or 0x, then optimise hot functions or move them to workers.

20What is the libuv thread pool used for?Often asked

Operations without non-blocking OS APIs: file system calls, DNS lookups via dns.lookup, some crypto (pbkdf2, scrypt) and zlib. It defaults to 4 threads, configurable with UV_THREADPOOL_SIZE. Network sockets do not use it.

21What does EventEmitter do?Often asked

It implements the observer pattern: objects emit named events and listeners registered with on or once run when they fire. Many core APIs (streams, HTTP servers, processes) are emitters. Unhandled error events throw, so always listen for them.

22How do you secure a Node.js app?Often asked

Validate input, use parameterised queries, keep dependencies updated and audited (npm audit), set security headers, avoid eval and shelling out with user input, store secrets in environment variables or a secret manager, rate-limit, and run with least privilege. Node's permission model can restrict file system and network access.

23What is the fetch API in Node?Often asked

Node 18+ includes a global fetch based on undici, with Request, Response, Headers and streaming bodies, so most apps no longer need node-fetch or axios for HTTP calls.

24How do you handle large JSON payloads efficiently?Often asked

Stream them with a streaming parser, limit request body size, paginate API responses, compress responses, and avoid holding entire datasets in memory.

25What is the permission model?Often asked

Recent Node versions offer a permission model (--permission) that restricts file system, child process and worker access unless explicitly allowed, adding defence in depth for scripts.

26What is package.json exports used for?Often asked

It defines a package's public entry points and conditional exports for import vs. require, Node vs. browser, and hides internal files from consumers.

27How do timers and AbortController work together?Often asked

Many Node APIs accept an AbortSignal: AbortSignal.timeout(5000) cancels fetches or stream reads after a deadline, and timers/promises setTimeout can be awaited and aborted.

28What is the difference between require caching and ESM loading?Often asked

CommonJS modules are cached in require.cache after first load, synchronously. ES modules are loaded asynchronously, cached by URL, support top-level await, and their bindings are live.

29What has Node added natively in recent versions?Sometimes asked

Built-in fetch and Web Streams, a test runner (node --test), watch mode (--watch), .env file loading (--env-file), a permission model, TypeScript type stripping for running .ts files, and a built-in SQLite module.

30What is node --watch?Sometimes asked

A built-in watch mode that restarts the process when files change, replacing nodemon for many projects.

Objective questions 30

1Node.js runs JavaScript on…Asked almost every time
  1. AThe GPU
  2. BOne process per request
  3. CMany threads by default
  4. DA single main thread with an event loopCorrect answer

Why: I/O is offloaded; JS runs on one thread.

2Which module runs JavaScript in parallel threads?Asked almost every time
  1. Aworker_threadsCorrect answer
  2. Bchild_process only
  3. Cevents
  4. Dcluster

Why: worker_threads gives real parallel JS threads.

3Which runs first?Asked almost every time
  1. Aan I/O callback
  2. BsetTimeout(fn, 0)
  3. CsetImmediate
  4. Dprocess.nextTickCorrect answer

Why: nextTick runs before promise microtasks and the next phase.

4Which signal should trigger graceful shutdown in containers?Asked almost every time
  1. ASIGTERMCorrect answer
  2. BSIGKILL
  3. CSIGHUP only
  4. DSIGSTOP

Why: SIGKILL cannot be caught.

5What happens when synchronous code runs for 2 seconds?Asked almost every time
  1. ANothing
  2. BAll other requests waitCorrect answer
  3. CNode spawns a new thread
  4. DIt runs in the background

Why: It blocks the event loop.

6Which API keeps request context across async calls?Asked almost every time
  1. AEventEmitter
  2. BAsyncLocalStorageCorrect answer
  3. Cprocess.env
  4. Dglobal variables

Why: Used for request IDs.

7What is the best way to pipe streams with error handling?Very often asked
  1. Awhile loop
  2. Ba.pipe(b) only
  3. Cstream.pipelineCorrect answer
  4. Dfs.readFileSync

Why: pipeline forwards errors and cleans up.

8What does write() returning false signal?Very often asked
  1. AThe write failed
  2. BBackpressure: wait for 'drain'Correct answer
  3. CThe stream closed
  4. DNothing

Why: The buffer is full.

9Default size of the libuv thread pool?Very often asked
  1. A16
  2. BNumber of CPUs
  3. C1
  4. D4Correct answer

Why: Set UV_THREADPOOL_SIZE to change it.

10What should happen after an uncaughtException?Very often asked
  1. AIgnore it
  2. BLog and exit; let a supervisor restartCorrect answer
  3. CRetry the request
  4. DIncrease memory

Why: The process may be in an unknown state.

11Which function measures event loop delay?Very often asked
  1. Aprocess.uptime
  2. Bos.loadavg only
  3. CsetImmediate
  4. DmonitorEventLoopDelayCorrect answer

Why: From perf_hooks.

12Which child_process method avoids a shell?Very often asked
  1. Ashell
  2. BexecFileCorrect answer
  3. Cexec
  4. Dsystem

Why: Safer against injection.

13Which flag records a CPU profile?Very often asked
  1. A--heap
  2. B--cpu-profCorrect answer
  3. C--trace
  4. D--profile-all

Why: Open in DevTools.

14Global fetch in Node is based on…Very often asked
  1. Agot
  2. BundiciCorrect answer
  3. Caxios
  4. Drequest

Why: Built in since Node 18.

15Which cancels an operation after 5 seconds?Very often asked
  1. Aprocess.abort()
  2. BPromise.timeout
  3. CAbortSignal.timeout(5000)Correct answer
  4. DsetTimeout(cancel)

Why: Pass the signal to the API.

16Which uses all CPU cores with several processes sharing a port?Often asked
  1. Autil module
  2. Bcluster moduleCorrect answer
  3. Cevents module
  4. Dpath module

Why: cluster forks workers behind one port.

17Which field makes .js files ES modules?Often asked
  1. A"type": "module"Correct answer
  2. B"esm": true
  3. C"main": "esm"
  4. D"module": true

Why: Set it in package.json.

18Which flag opens the debugger for DevTools?Often asked
  1. A--debug-port
  2. B--trace
  3. C--prof only
  4. D--inspectCorrect answer

Why: Then attach Chrome DevTools.

19Unhandled 'error' events on an EventEmitter…Often asked
  1. ARetry automatically
  2. BAre ignored
  3. CThrow and can crash the processCorrect answer
  4. DAre logged only

Why: Always attach an error listener.

20Where does a Buffer's memory live?Often asked
  1. AOn disk
  2. BIn the GPU
  3. COutside the V8 heapCorrect answer
  4. DIn the call stack

Why: Raw binary data.

21Which package.json field defines public entry points?Often asked
  1. Abin
  2. BexportsCorrect answer
  3. Cfiles
  4. Dmain only

Why: Supports conditions.

22Which flag restarts Node on file changes?Often asked
  1. A--reload
  2. B--live
  3. C--hot
  4. D--watchCorrect answer

Why: Built in since Node 18; replaces nodemon.

23Which starts another Node process with IPC?Often asked
  1. Aexec
  2. Bcluster.run
  3. CforkCorrect answer
  4. Dspawn only

Why: child_process.fork.

24Which flag enables the permission model?Often asked
  1. A--permissionCorrect answer
  2. B--secure
  3. C--sandbox
  4. D--no-fs

Why: Restricts fs and child processes.

25Which ESM feature does CommonJS lack?Often asked
  1. ATop-level awaitCorrect answer
  2. BCaching
  3. CExports
  4. DJSON imports

Why: ESM loads asynchronously.

26Which built-in command runs tests without a library?Sometimes asked
  1. Anode --spec
  2. Bnode --testCorrect answer
  3. Cnode test
  4. Dnpm jest

Why: Node ships a test runner.

27Which flag loads environment variables from a file natively?Sometimes asked
  1. A--vars
  2. B--env-file=.envCorrect answer
  3. C--dotenv
  4. D--config .env

Why: Available in modern Node versions.

28Which module handles file paths portably?Sometimes asked
  1. ApathCorrect answer
  2. Burl
  3. Cos
  4. Dfs

Why: path joins and normalises paths across platforms.

29Which tool draws flame graphs for Node?Sometimes asked
  1. Apm2 only
  2. Bclinic.jsCorrect answer
  3. Ceslint
  4. Dnodemon

Why: 0x also draws flame graphs.

30Where are CommonJS modules cached?Sometimes asked
  1. Amodule.paths
  2. Bprocess.cache
  3. Crequire.cacheCorrect answer
  4. Dimport.meta

Why: After first load.

Track what you have practised and search every bank in your dashboard.

Start learning