Node JS Interview Questions and Answers for Freshers and Experienced
Quick answer
Fifteen Node.js interview questions with short correct answers, tested code snippets and a mock round plan.
Node js interview questions mostly test five areas: how the event loop schedules callbacks, how you handle asynchronous errors, when to use streams, how modules work, and how you keep CPU-heavy work off the main thread. Freshers are asked to predict output and explain concepts. Experienced candidates are asked to debug, scale and secure an Express or NestJS service.
Key takeaways
- Know the event loop phases in order: timers, pending callbacks, idle and prepare, poll, check, close callbacks.
- Inside an I/O callback,
setImmediatealways runs before a zero-delaysetTimeout. In the main module the order is not guaranteed. - Worker threads are for CPU-intensive JavaScript. The Node.js documentation says they do not help much with I/O-intensive work.
- Practise by typing snippets and predicting output before running them. Reading answers alone does not hold up in a live round.
On this page:
- What do interviewers ask at each experience level?
- Which core concept questions come first?
- How do you answer event loop output questions?
- What do they ask about promises and error handling?
- Which stream and module questions are common?
- What is asked about performance, scaling and security?
- Frequently asked questions
What do interviewers ask at each experience level?
The topics stay the same and the depth changes. Use this table to decide where to spend your preparation hours.
| Level | Typical question style | Topics to be solid on | What a strong answer includes |
|---|---|---|---|
| Fresher or intern | "What is X?" and "Predict the output" | Event loop basics, callbacks vs promises, modules, npm, a simple Express route | A correct definition plus one small example |
| 1 to 3 years | "How did you handle X in your project?" | Error handling, middleware, streams, JWT sessions, database queries, testing | A real decision you made and its trade-off |
| 3 years and above | "This service is slow or crashing. What do you check?" | Profiling, memory leaks, clustering, worker threads, queues, graceful shutdown | A debugging sequence, with metrics you would look at |
Which core concept questions come first?
Almost every interview opens with what Node.js is and why it is single-threaded. Answer these in two or three sentences each.
1. What is Node.js and where does it fit?
Node.js is a JavaScript runtime that runs outside the browser. It suits I/O-heavy services such as REST APIs, real-time chat and API gateways, because it can wait on many network and disk operations without one thread per request.
2. Is Node.js single-threaded?
Your JavaScript runs on one main thread by default. The official Node.js event loop guide explains that the event loop allows non-blocking I/O despite the single JavaScript thread by offloading operations to the system kernel whenever possible. So the honest answer is "one thread for your code, with I/O handled outside it".
3. What is the difference between blocking and non-blocking code?
fs.readFileSync stops everything until the file is read. fs.readFile or fs.promises.readFile lets the loop serve other requests meanwhile. In a server, a blocking call inside a request handler delays every other user.
4. What is middleware in Express?
A function with the signature (req, res, next) that runs in order before the route handler. Common uses: parsing JSON, logging, authentication, and a final error handler with four arguments (err, req, res, next).
5. Which Node.js version should a production app use?
The Node.js release page says production applications should use only Active LTS or Maintenance LTS releases, and that, historically, even-numbered major versions moved to LTS after six months as Current. Check the release page for the current schedule.
How do you answer event loop output questions?
Apply three rules in order: synchronous code first, then the microtask queues (process.nextTick before promises), then the event loop phases. Try this trace.
const fs = require("node:fs");
fs.readFile(__filename, () => {
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
});Output:
sync
nextTick
promise
immediate
timeoutTrace it aloud in the interview. sync prints because it is ordinary code. The nextTick queue drains next, then the promise microtask. The callback is running inside an I/O cycle, so the loop moves from the poll phase to the check phase, where setImmediate lives, before it wraps around to timers. The Node.js guide states that within an I/O cycle the immediate callback is always executed first.
6. Follow-up: what if the same lines are at the top of the file?
Then timeout and immediate can appear in either order, because it depends on process performance at startup. Saying "non-deterministic in the main module" is the answer interviewers want.
What do they ask about promises and error handling?
Expect questions on running tasks in parallel and on what happens when one of them fails. The safest way to answer is with a short snippet.
7. What is the difference between Promise.all and Promise.allSettled?
const wait = (ms, ok) =>
new Promise((resolve, reject) =>
setTimeout(() => (ok ? resolve(ms) : reject(new Error("failed " + ms))), ms)
);
async function main() {
const results = await Promise.allSettled([wait(10, true), wait(20, false)]);
console.log(results.map((r) => r.status)); // [ 'fulfilled', 'rejected' ]
try {
await Promise.all([wait(10, true), wait(20, false)]);
} catch (err) {
console.log(err.message); // failed 20
}
}
main();Promise.all rejects as soon as one promise rejects. Promise.allSettled waits for all and reports each status. Use the second when partial success is acceptable, such as bulk notifications.
8. How do you handle errors in async route handlers?
Wrap the body in try/catch and pass the error to next(err), or use a wrapper that does this for every handler. Keep one central error middleware that logs and returns a clean JSON response.
These questions overlap heavily with the language round, so revise closures, this and the browser event loop from the JavaScript interview questions set as well.
Which stream and module questions are common?
Interviewers use streams to check whether you think about memory, and modules to check whether you have worked on a current codebase.
9. What are streams and what types exist?
Streams process data in chunks instead of loading it all into memory. The Node.js stream documentation lists four fundamental types: Writable, Readable, Duplex (both) and Transform (a Duplex that modifies data as it passes through).
10. How would you compress a 2 GB log file?
const fs = require("node:fs");
const zlib = require("node:zlib");
const { pipeline } = require("node:stream/promises");
async function compress(file) {
await pipeline(
fs.createReadStream(file),
zlib.createGzip(),
fs.createWriteStream(file + ".gz")
);
console.log("compressed", file);
}
compress(process.argv[2]).catch((err) => console.error("failed:", err.message));Run it as node compress.js app.log. pipeline connects the streams, handles backpressure so a fast reader does not flood a slow writer, and rejects if any stage fails. Reading the whole file with readFile would hold 2 GB in memory.
11. What is the difference between CommonJS and ES modules?
CommonJS uses require and module.exports. ES modules use import and export. According to the Node.js ES modules documentation, a file is treated as an ES module if it has the .mjs extension or the nearest package.json has "type": "module", and __dirname and __filename are not available there. Use import.meta.dirname and import.meta.filename instead.
What is asked about performance, scaling and security?
For candidates with experience, the round becomes a conversation about a slow or failing service. Structure your answer as "measure, find the blocking part, then fix".
12. A request that resizes images blocks the whole API. What do you do?
Image resizing is CPU work on the main thread. Move it to a worker thread or a separate queue-based service. The worker threads documentation says workers are useful for CPU-intensive JavaScript operations and do not help much with I/O-intensive work, because built-in asynchronous I/O is already more efficient.
13. How do you use all CPU cores?
Run multiple processes: the cluster module, a process manager, or several containers behind a load balancer. Keep the app stateless, with sessions in a shared store such as Redis, so any process can serve any request.
14. How do you find a memory leak?
Watch heap usage over time, take two heap snapshots a few minutes apart using the inspector, and compare what grew. Usual causes: unbounded in-memory caches, listeners that are never removed, and timers that are never cleared.
15. How do you secure a Node.js API?
Validate every input, use parameterised queries, hash passwords with a slow algorithm such as bcrypt or argon2, keep secrets in environment variables, set rate limits, and audit dependencies. Return correct status codes, which are covered in this explainer on REST API methods and status codes.
A 30-minute mock round you can run with a friend
- 10 minutes: two output-prediction snippets, answered aloud before running.
- 10 minutes: build
GET /users/:idwith validation and central error handling. - 10 minutes: "this endpoint takes four seconds, why?" Walk through database indexes, N+1 queries and blocking code.
Next step: pick one project on your resume and prepare a two-minute explanation of its request flow from route to database to response. Then widen your preparation with full stack developer interview questions and a first pass at system design basics for freshers, since both are often asked in the same loop.
Frequently asked questions
Are Node.js interviews hard for freshers?
They are manageable if your JavaScript basics are strong. Freshers are usually asked about the event loop, callbacks versus promises, modules and a simple Express API. Being able to predict the output of short asynchronous snippets matters more than memorising definitions.
Do I need to know Express for a Node.js interview?
In most cases, yes. Express remains a common choice for building APIs with Node.js, so expect questions on routing, middleware order and error handling. If the job description names NestJS or Fastify, prepare the equivalent concepts in that framework too.
What is the most important Node.js topic to prepare?
The event loop. It explains why Node.js handles many connections on one thread, why blocking code hurts every user, and how timers, promises and process.nextTick are ordered. Most other questions build on it.
Is Node.js single-threaded or multi-threaded?
Your JavaScript code runs on a single main thread by default. I/O is offloaded to the operating system or a background thread pool, and you can create worker threads for CPU-intensive tasks. So Node.js is single-threaded for your code but not for everything it does.
How many Node.js questions should I practise before an interview?
Quality matters more than count. Around twenty questions that you can answer with a working code example, covering the event loop, async errors, streams, modules and scaling, is a solid base. Add questions specific to the projects on your resume.