---
title: Node.js Interview Questions and Answers (36, with Code)
url: https://www.masaischool.com/resources/nodejs-interview-questions
description: 36 Node.js interview questions and answers for freshers and experienced: event loop, CJS vs ESM, streams, async, Express 5, security. Code run on Node 24.
updated: 2026-11-25
publisher: Masai (https://www.masaischool.com)
---

# Node.js Interview Questions and Answers: 36 Questions from Event Loop to Express 5

> **Short answer**
>
> Node.js interviews test the event loop, CommonJS versus ES modules, streams, promises and async/await, error handling, Express, security, testing and scaling. As of 25 November 2026, Node.js 26 is the Active LTS release, 24 and 22 are in maintenance and 27 is an alpha. These 36 answers note the Node.js version wherever behaviour changed.

This page is for students, freshers and working developers in India preparing for a Node.js, MERN or backend round. Questions are grouped by topic, and each group runs from fresher level to experienced level. Version facts were read on 25 November 2026 from the [Node.js releases page](https://nodejs.org/en/about/previous-releases), the [release schedule](https://github.com/nodejs/Release) and the Node.js v26 API documentation.

Every JavaScript block except the Express one was run on Node.js v24.15.0 and the output shown is the real output. The Express block was proofread only, because Express was not installed. For the language itself, practise with the [JavaScript practice projects](https://www.masaischool.com/resources/projects/javascript-practice-projects). For the wider path, see the [backend developer roadmap](https://www.masaischool.com/resources/backend-developer-roadmap).

1. **Runtime** - event loop, modules, the thread pool
2. **Async code** - promises, streams, errors
3. **Web layer** - Express, security, tests
4. **Production** - scaling, memory, shutdown
Interviewers usually move through these four areas in order.

## Which Node.js version to prepare for

| Release line | Status on 25 November 2026 | Latest version | End of life |
|---|---|---|---|
| Node.js 27 | Alpha. Scheduled to become Current on 22 April 2027 and LTS in October 2027 | 27.0.0 alpha builds | 30 April 2030 |
| Node.js 26 (Lithium) | Active LTS since 28 October 2026 | 26.13.1 (10 November 2026) | 30 April 2029 |
| Node.js 24 (Krypton) | Maintenance LTS since 20 October 2026 | 24.22.3 (10 November 2026) | 30 April 2028 |
| Node.js 22 (Jod) | Maintenance LTS | 22.23.5 (11 November 2026) | 30 April 2027 |
| Node.js 20 and 25 | End of life (30 April 2026 and 1 June 2026) | 20.20.2 and 25.9.0 | Passed |

The release model changed this year. Up to Node.js 26, odd-numbered releases lasted about six months and even-numbered ones became LTS (long-term support). The releases page says that from Node.js 27 the cycle is annual: every major version gets an alpha phase, six months as Current, and then LTS. So on 25 November 2026 no line has Current status. Prepare on Node.js 24 or 26, and say which one you used.

## Event loop and modules (Q1 to Q12)

### Runtime and event loop

- **Q1. What is Node.js?** A JavaScript runtime built on the V8 engine, with libuv providing the event loop and asynchronous I/O (input and output). It runs JavaScript outside the browser, so the same language serves both ends of a [full stack](https://www.masaischool.com/resources/full-stack-developer-roadmap).
- **Q2. Is Node.js single-threaded?** Your JavaScript runs on one thread, but the process is not single-threaded. libuv keeps a thread pool for file system work and DNS lookups (default size 4, set with UV_THREADPOOL_SIZE, maximum 1024), and network sockets are handled by the operating system kernel.
- **Q3. What is the event loop?** The loop that lets one JavaScript thread serve many connections by handing I/O to the kernel or thread pool and running callbacks when results arrive. Its phases are timers, pending callbacks, poll, check and close callbacks, as described in the [official event loop guide](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick).
- **Q4. setTimeout(fn, 0) or setImmediate(fn): which runs first?** Inside an I/O callback, setImmediate always runs first because the check phase follows poll. Called from the main module, the order can vary with process timing. The code below shows the I/O case.
- **Q5. What is process.nextTick() and how does it differ from a promise callback?** Both run before the loop continues to its next phase. The next-tick queue is drained first, then promise microtasks. Recursive nextTick calls can starve I/O, so prefer queueMicrotask or setImmediate in new code.
- **Q6. What blocks the event loop?** Any long synchronous work: a heavy loop, a *Sync file call, parsing a huge JSON string, or a slow regular expression. While it runs, no other request is served. Q32 shows a measurement.
const fs = require("node:fs"); console.log("1 sync start"); process.nextTick(() => console.log("3 nextTick")); Promise.resolve().then(() => console.log("4 promise microtask")); fs.readFile(__filename, () => { // callback runs in the poll phase setTimeout(() => console.log("7 setTimeout 0"), 0); setImmediate(() => console.log("6 setImmediate")); process.nextTick(() => console.log("5 nextTick inside I/O callback")); }); console.log("2 sync end");

The numbers in the strings are the order in which Node.js 24 printed the lines: synchronous code, then the next-tick queue, then promise microtasks, then (after the file read) next tick, setImmediate and finally the timer.

### Modules: CommonJS (CJS) and ES modules (ESM)

| Point | CommonJS | ES modules |
|---|---|---|
| Syntax | require() and module.exports | import and export |
| How Node.js picks it | .cjs files, or .js when package.json has no "type": "module" | .mjs files, or .js when package.json has "type": "module" |
| Loading | Synchronous, at the point of the call | Parsed first, then linked and evaluated. Top-level await is allowed |
| File path helpers | __filename, __dirname | import.meta.filename, import.meta.dirname (added in 21.2 and 20.11) |
| Loading the other kind | require() of a synchronous ES module, or import() for any | import works for CommonJS modules in most cases |

- **Q7. What is the difference between CommonJS and ES modules?** See the table. ESM is the JavaScript standard and allows static analysis. CJS is the original Node.js system and still common in older code.
- **Q8. Can you require() an ES module?** Yes, in current versions. The docs mark it as no longer experimental from v25.4.0 and unflagged from v22.12.0 and v20.19.0. The module must have no top-level await, otherwise Node.js throws ERR_REQUIRE_ASYNC_MODULE and you must use import().
- **Q9. module.exports or exports?**exports is a shortcut variable that starts out pointing at module.exports. Adding properties to it works. Reassigning it (exports = fn) breaks the link, so the caller still receives the old object.
- **Q10. How does module caching work?** A CommonJS module runs once. Later require() calls for the same resolved file return the cached module.exports, so module-level state is shared across the app. That is why a database client is usually created in one module.
- **Q11. What is the difference between dependencies and devDependencies, and what does package-lock.json do?** Runtime packages go in dependencies. Build and test tools go in devDependencies. The lock file records the exact version of every installed package so each machine installs the same tree. Use npm ci in pipelines.
- **Q12. Can Node.js run TypeScript?** Yes, for erasable syntax. Type stripping was added in v22.6.0 and marked stable in v25.2.0 and v24.12.0. Node.js removes the types and does no type checking, so run tsc separately.

## Async patterns, streams and errors (Q13 to Q22)

- **Q13. Callbacks, promises or async/await?** Callbacks follow the error-first style (err, data) and nest badly. Promises chain and have one error path. async/await is syntax over promises and reads like synchronous code. Core modules offer promise versions such as node:fs/promises.
- **Q14. Promise.all, allSettled, race and any?**all rejects on the first failure and keeps input order. allSettled waits for everything and reports each status. race settles with the first to settle. any resolves with the first success.
- **Q15. How do you run tasks in parallel but limit concurrency?** Start promises without awaiting each one, then await Promise.all. For a large list, process it in batches or keep a small pool of workers pulling from a queue, so you do not open thousands of connections at once.
- **Q16. What is an EventEmitter?** The class behind most Node.js objects, including streams and servers. on adds a listener, once adds a one-shot listener and emit calls listeners synchronously in the order added. An error event with no listener throws.
const { setTimeout: sleep } = require("node:timers/promises"); async function fetchPrice(id, ms, fail = false) { await sleep(ms); if (fail) throw new Error(`price service failed for ${id}`); return { id, price: id * 100 }; } async function main() { const all = await Promise.all([fetchPrice(1, 30), fetchPrice(2, 10)]); console.log(all.map((p) => p.price)); // order of input, not of finish const settled = await Promise.allSettled([fetchPrice(3, 10), fetchPrice(4, 5, true)]); console.log(settled.map((r) => r.status)); try { await Promise.all([fetchPrice(5, 10), fetchPrice(6, 5, true)]); } catch (err) { console.log("caught:", err.message); // first rejection wins } const fastest = await Promise.race([fetchPrice(7, 30), fetchPrice(8, 5)]); console.log("race winner:", fastest.id); } main();[ 100, 200 ] [ 'fulfilled', 'rejected' ] caught: price service failed for 6 race winner: 8

- **Q17. What are streams and what types exist?** Streams process data in chunks, so a file larger than memory can still be read. The four types are Readable, Writable, Duplex (both, such as a TCP socket) and Transform (a Duplex that changes data, such as gzip).
- **Q18. What is backpressure?** When the writer is slower than the reader, data piles up in memory. write() returns false once the buffer passes highWaterMark (65536 bytes by default on Node.js 24, or 16 objects in object mode), and the producer should wait for the drain event.
- **Q19. pipe() or pipeline()?**pipe() connects streams but does not forward errors or clean up. pipeline() forwards errors, destroys every stream on failure and tells you when it is done. Use the promise version from node:stream/promises.
- **Q20. What is a Buffer?** A fixed-length sequence of bytes, a subclass of Uint8Array, used for binary data such as files and network packets. Convert with buf.toString("utf8") and Buffer.from(text).
const { Readable, Transform } = require("node:stream"); const { pipeline } = require("node:stream/promises"); const upper = new Transform({ transform(chunk, encoding, callback) { callback(null, chunk.toString().toUpperCase()); // null means no error }, }); async function main() { const source = Readable.from(["node ", "streams ", "handle ", "backpressure\n"]); await pipeline(source, upper, process.stdout, { end: false }); console.log("pipeline finished"); } main().catch((err) => { console.error("pipeline failed:", err.message); process.exitCode = 1; });

This printed NODE STREAMS HANDLE BACKPRESSURE and then pipeline finished.

- **Q21. Operational or programmer errors?** Operational errors are expected run-time failures: a timeout, a missing file, bad input. Handle them and respond. Programmer errors are bugs, such as reading a property of a null value. Log them, let the process exit and let a supervisor restart it.
- **Q22. What happens to an unhandled promise rejection?** Since Node.js 15 the default mode is throw: if no unhandledRejection handler is set, the rejection is raised as an uncaught exception and the process exits. Catch errors where you can act on them, and keep the original with { cause }.
class NotFoundError extends Error { constructor(message, options) { super(message, options); // options.cause keeps the original error this.name = "NotFoundError"; this.statusCode = 404; } } async function findUser(id) { try { JSON.parse("{ bad json"); // stands in for a failing lower-level call } catch (err) { throw new NotFoundError(`user ${id} not found`, { cause: err }); } } process.on("unhandledRejection", (reason) => { console.log("unhandledRejection:", reason.message); }); async function main() { try { await findUser(42); } catch (err) { console.log(err.name, err.statusCode, err.message); console.log("cause is a", err.cause.name); } Promise.reject(new Error("nobody awaited this")); // reaches the process hook } main();NotFoundError 404 user 42 not found cause is a SyntaxError unhandledRejection: nobody awaited this

## Express, security and testing (Q23 to Q31)

The Express home page showed version 5.3.0 on 25 November 2026. The snippet below is Express 5 style and was not executed here.// Express 5. Not executed for this page: needs `npm install express`. const express = require("express"); const app = express(); app.use(express.json()); // middleware: parse JSON bodies app.get("/users/:id", async (req, res) => { const user = await findUser(req.params.id); // a rejection here reaches the error handler if (!user) return res.status(404).json({ error: "User not found" }); res.json(user); }); app.use((err, req, res, next) => { // four arguments: error-handling middleware console.error(err); res.status(500).json({ error: "Internal server error" }); }); app.listen(3000);

- **Q23. What is middleware?** A function (req, res, next) that runs in the order registered. It can read or change the request, end the response, or call next(). Logging, body parsing and authentication are all middleware.
- **Q24. How does error handling work in Express?** An error handler takes four arguments, (err, req, res, next), and is registered last. Calling next(err) skips to it. In Express 5, a handler that returns a rejected promise calls next automatically, so async handlers need no wrapper.
- **Q25. req.params, req.query or req.body?**params holds route segments such as :id. query holds the parsed query string. body holds the parsed payload and needs middleware such as express.json(). Treat all three as untrusted input.
- **Q26. How do you design a REST API in Express?** Use nouns for resources, HTTP methods for actions, correct status codes (201 for created, 400 for bad input, 404 for missing), validation at the edge, pagination for lists and one error format. Group routes with express.Router().
- **Q27. How do you secure an Express app?** The Express security guide lists: keep Express and dependencies current, use TLS, never trust user input, set headers with Helmet, reduce fingerprinting, set cookie options, limit login attempts and run npm audit.
- **Q28. How do you prevent injection attacks?** Use parameterised queries or an ORM (object-relational mapper) instead of building SQL strings, validate types so an object cannot arrive where a string is expected in a MongoDB filter, and never pass request data to eval or a shell command.
- **Q29. Where do secrets go, and how are passwords stored?** Secrets go in environment variables or a secrets manager, never in Git. node --env-file=.env loads a file without a package. Passwords are stored as slow, salted hashes (scrypt in node:crypto, bcrypt or Argon2), never encrypted or plain.
- **Q30. What is the Node.js permission model?** The --permission flag makes the process deny file system, child process and worker access unless you grant it with allow flags. The docs mark it stable from v23.5.0 and v22.13.0. It limits damage from a compromised dependency.
- **Q31. How do you test Node.js code?** The built-in node:test runner has been stable since v20, with node:assert, mocks and node --test to find test files. Jest, Vitest and Mocha remain common. Test pure functions directly and HTTP routes through the app.
const test = require("node:test"); const assert = require("node:assert/strict"); function slugify(title) { return title.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); } test("slugify makes URL-safe slugs", () => { assert.equal(slugify(" Node.js Interview Questions! "), "node-js-interview-questions"); }); test("async code and mocks", async (t) => { const sendMail = t.mock.fn(async () => "queued"); assert.equal(await sendMail("a@example.com"), "queued"); assert.equal(sendMail.mock.callCount(), 1); });

Running the file with node reported tests 2, pass 2, fail 0.

## Performance and scaling (Q32 to Q36)const { performance } = require("node:perf_hooks"); const start = performance.now(); setTimeout(() => { const late = performance.now() - start; console.log("10 ms timer fired late:", late > 100); }, 10); let total = 0; // CPU-bound loop: nothing else can run const until = performance.now() + 150; while (performance.now() < until) total += 1; console.log("sync loop done");

Output: sync loop done, then 10 ms timer fired late: true. The 10 ms timer could not fire until the 150 ms loop finished.

- **Q32. How do you handle CPU-heavy work?** Keep it off the main thread. Use worker_threads, which the docs recommend for CPU-intensive JavaScript and which can share memory. Or move the job to a queue and a separate service. Workers do not help I/O-bound code.
- **Q33. Cluster, worker threads or child processes?**cluster runs several Node.js processes that share a server port, for using all cores. worker_threads runs threads inside one process. child_process starts any external program. Many teams let a container platform or PM2 run the copies instead of cluster.
- **Q34. How do you find a memory leak?** Watch process.memoryUsage() over time, take heap snapshots with --inspect and Chrome DevTools, and compare them. Usual causes: caches that never evict, listeners never removed, timers never cleared and large objects held in closures.
- **Q35. How do you shut down gracefully?** On SIGTERM, stop accepting connections with server.close(), finish in-flight requests, close database pools, then exit. Add a timeout so a stuck connection cannot hold the process open.
- **Q36. How do you make a slow endpoint faster?** Measure first. Then check the usual suspects: queries without an index or made one per row, awaits run in sequence that could run together, missing caching, large payloads sent without streaming or compression, and synchronous work on the event loop. Database questions follow, so revise the [SQL interview questions](https://www.masaischool.com/resources/sql-interview-questions).

## How to prepare in two weeks

1. Install Node.js 24 or 26 and run every snippet on this page. Change the order of lines in the event loop example and predict the output before running it.
2. Build one small REST API with Express, a database, validation, an error handler and five tests. The [backend project ideas](https://www.masaischool.com/resources/projects/backend-project-ideas) list has options sized for a week.
3. Write answers to Q2 to Q6, Q7, Q18, Q22 and Q24 in your own words. In our reading these come up most, but no company publishes its question bank.
4. For product company rounds, add data structures practice from the [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions) and, for experienced roles, [system design preparation](https://www.masaischool.com/resources/system-design-interview-preparation).
5. If the role is MERN, pair this page with the [React interview questions](https://www.masaischool.com/resources/react-interview-questions).

## Frequently asked questions

### What are the most asked Node.js interview questions?

The event loop and its phases, whether Node.js is single-threaded, process.nextTick versus setImmediate, CommonJS versus ES modules, streams and backpressure, promise error handling, Express middleware and how to scale across CPU cores. Start with Q2 to Q7, Q18, Q22 and Q24. No company publishes its question bank, so this is our reading.

### Which Node.js version should I learn in 2026?

As of 25 November 2026, Node.js 26 is the Active LTS release, and Node.js 24 and 22 are in maintenance. Node.js 27 is an alpha that is scheduled to become Current in April 2027. Learn on 24 or 26. The code on this page was run on 24.15.0.

### Is Node.js single-threaded or multi-threaded?

JavaScript code runs on a single thread with one event loop. The process also has a libuv thread pool (default size 4) for file system and DNS work, and you can start more JavaScript threads with worker_threads. So the accurate answer is: single-threaded JavaScript on a multi-threaded runtime.

### What Node.js questions are asked for freshers?

Freshers are usually asked what Node.js is, how it differs from browser JavaScript, what npm and package.json do, require versus import, callbacks versus promises versus async/await, a simple Express route with middleware, and basic error handling. Q1, Q7, Q11, Q13, Q14, Q23 and Q25 cover these.

### What is the difference between Node.js and Express.js?

Node.js is the runtime that executes JavaScript and provides modules such as http, fs and stream. Express is a web framework that runs on Node.js and adds routing, middleware and request and response helpers. You can build a server with Node.js alone, but most teams use a framework.

### Do I need DSA for a Node.js developer interview?

For most product companies, yes: expect one or two rounds on arrays, strings, hash maps and complexity before the Node.js round. Service companies and startups often focus more on JavaScript, an API task and a project discussion. Prepare both unless the recruiter tells you otherwise.

## Sources checked

- [Release status table (v27 Alpha, v26/v24/v22 LTS, v25 and v20 EOL) and the annual release cycle from Node.js 27](https://nodejs.org/en/about/previous-releases)
- [Start, LTS, maintenance and end-of-life dates per release line](https://raw.githubusercontent.com/nodejs/Release/main/schedule.json)
- [Latest version numbers and release dates per line](https://nodejs.org/dist/index.json)
- [Event loop phases, nextTick queue, setImmediate vs setTimeout](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick)
- [Thread pool default size 4, UV_THREADPOOL_SIZE, maximum 1024, used for fs and getaddrinfo](https://docs.libuv.org/en/v1.x/threadpool.html)
- [require() of ES modules: version history and requirements; module caching](https://nodejs.org/api/modules.html)
- [import.meta.dirname and import.meta.filename versions; differences from CommonJS](https://nodejs.org/api/esm.html)
- [Type stripping added v22.6.0, stable v25.2.0 and v24.12.0, no type checking](https://nodejs.org/api/typescript.html)
- [Stream types, highWaterMark, pipeline()](https://nodejs.org/api/stream.html)
- [--unhandled-rejections default throw since v15; --env-file](https://nodejs.org/api/cli.html)
- [Permission Model stable from v23.5.0 and v22.13.0, --permission flag](https://nodejs.org/api/permissions.html)
- [node:test stable since v20.0.0](https://nodejs.org/api/test.html)
- [Workers are for CPU-intensive JavaScript and can share memory](https://nodejs.org/api/worker_threads.html)
- [Cluster runs multiple Node.js processes](https://nodejs.org/api/cluster.html)
- [Buffer is a fixed-length sequence of bytes and a subclass of Uint8Array](https://nodejs.org/api/buffer.html)
- [Express version 5.3.0 shown on the home page](https://expressjs.com/)
- [Four-argument error handlers; Express 5 calls next() for rejected promises](https://expressjs.com/en/guide/error-handling.html)
- [Security checklist: TLS, Helmet, input, cookies, brute force, npm audit](https://expressjs.com/en/advanced/best-practice-security.html)
