Skip to main content
CodingMarble

Interview questions and cheat sheets

Node.js Interview Questions and Answers for Developers

Node.js interviews test whether you understand one idea: a single JavaScript thread that never waits, supported by an event loop and a pool of helpers. The sixteen answers below build from that idea toward streams, concurrency, Express and the failures that show up in production.

By CodingMarble · Published · 6 min read

An empty notebook beside a keyboard and a pen
Photo: Marissa Grootes on Unsplash

The event loop and asynchronous code

1. How does the event loop work at a practical level?

Node runs your JavaScript on one thread. When code starts an operation such as a file read or a network request, Node hands it to the operating system or to a helper thread pool and continues. When the operation finishes, its callback is queued and the loop runs it as soon as the call stack is empty. The loop moves through phases: timers, pending I/O callbacks, a poll phase that waits for new I/O, a check phase for setImmediate, and close callbacks.

2. What does non-blocking I/O mean, and what can still block?

Non-blocking means the thread does not sit idle waiting for slow I/O, so one process can serve many connections. It does not make your own code fast. A long loop, a huge JSON.parse, a heavy regular expression or any synchronous method such as fs.readFileSync stalls every request until it returns. If one request can freeze all others, look for synchronous or CPU-heavy work on the main thread.

3. How do callbacks, promises and async/await relate?

They are three styles for the same thing. A callback is a function called when work completes, which nests badly and spreads error handling. A promise represents a future value and chains with then and catch. Async/await is syntax over promises that lets you write sequential-looking code and use try/catch. An async function always returns a promise, and awaiting independent tasks one after another wastes time, so start them together with Promise.all.

4. What is the difference between process.nextTick and setImmediate?

process.nextTick queues a callback to run right after the current operation, before the loop continues. In a CommonJS file it also runs before promise callbacks, while in an ES module the promise callback runs first. setImmediate runs in the check phase, after the poll phase. Overusing nextTick can starve I/O because the loop cannot proceed until the tick queue is empty. In the main module, the order of setTimeout 0 and setImmediate is not fixed, while inside an I/O callback setImmediate always comes first.

JavaScript· Ordering of the queues
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
// sync first; then nextTick and promise (order depends on module type); then timeout and immediate (order can vary)

Modules, streams and backpressure

5. How do CommonJS and ES modules differ?

CommonJS uses require and module.exports, loads synchronously and is the older default. ES modules use import and export, are parsed statically, support top-level await and are the standard shared with browsers. Node picks the system from the file extension (.mjs or .cjs) or the "type" field in package.json. Relative imports in ES modules need the file extension, and __dirname and require are not defined there.

JavaScript· The same export in both systems
// CommonJS
const path = require("node:path");
module.exports = { join: path.join };

// ES module
import path from "node:path";
export const join = path.join;

6. What are streams, and why use them?

A stream processes data in chunks instead of loading it all. Reading a large file with readFile holds the whole file in memory, while a read stream keeps memory use roughly constant. Streams come as readable, writable, duplex and transform types, and HTTP requests and responses are streams too. They suit large files, uploads, compression and proxying.

7. What is backpressure?

Backpressure is the signal that a consumer cannot keep up with a producer. If a fast readable feeds a slow writable, chunks pile up in memory. A writable's write method returns false when its buffer is full, and you should wait for the drain event before writing more. Using pipe or stream.pipeline handles this for you, and pipeline also destroys every stream and reports an error if any step fails.

JavaScript· Compress a file with pipeline, which handles backpressure and errors
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

await pipeline(
  createReadStream("access.log"),
  createGzip(),
  createWriteStream("access.log.gz")
);
console.log("done");

CPU-bound work, cluster and worker threads

8. When do you need cluster or worker threads?

Use them when one core is the limit. The cluster module starts several Node processes that share a server port, which helps use all cores for request handling. Worker threads run JavaScript in separate threads inside one process and fit CPU-heavy jobs such as image processing or large computations, with messages passed between threads. Neither helps with slow I/O, which the event loop already handles. Many teams scale with a process manager or containers instead of cluster; choose by how your deployment already works.

JavaScript· Move a heavy loop to a worker thread
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url), { workerData: 5_000_000 });
  worker.on("message", (sum) => console.log("sum:", sum));
  worker.on("error", console.error);
} else {
  let sum = 0;
  for (let i = 1; i <= workerData; i++) sum += i;
  parentPort.postMessage(sum);
}

Practical tip: to prove the event loop is blocked, log the time between a setInterval tick and its expected time. If a 100 ms interval keeps arriving late, some synchronous work is holding the thread, and a CPU profile will show which function.

Error handling and configuration

9. How should errors in async code be handled?

Inside async functions, wrap awaited calls in try/catch or let the rejection propagate to a single handler. A rejected promise that nobody handles triggers an unhandledRejection, which in current Node versions terminates the process by default. A try/catch cannot catch an error thrown inside a callback that runs later, such as one passed to setTimeout. Use the error-first callback convention or convert callbacks to promises with util.promisify.

JavaScript· Catching a rejection, and a last-resort logger
async function load() {
  throw new Error("boom");
}

try {
  await load();
} catch (err) {
  console.error("handled:", err.message);
}

process.on("unhandledRejection", (reason) => {
  console.error("unhandled:", reason);
  process.exitCode = 1;
});

10. How do you manage environment variables and config?

Read configuration from process.env, keep secrets out of the repository, and validate the values at startup so a missing variable fails immediately with a clear message. Environment variables are always strings, so convert numbers and booleans explicitly. Recent Node versions can load a .env file with the --env-file flag, and the dotenv package is the common alternative; confirm support in the documentation for your version.

11. How do you shut down gracefully?

Listen for SIGTERM and SIGINT, stop accepting new connections with server.close, let in-flight requests finish, close database connections, then exit. Without this, a deploy can cut requests in half. Add a timeout so a stuck connection cannot keep the process alive forever.

Express middleware and security basics

12. Why does middleware order matter in Express?

Express runs middleware and routes in the order they are registered, and each one either responds or calls next. A body parser registered after a route never sees that route's request, an authentication check placed after a route protects nothing, and a catch-all 404 handler must come last. Error-handling middleware takes four arguments, (err, req, res, next), and must be registered after the routes it covers. In Express 4, an error thrown in an async handler is not forwarded automatically, so wrap it or call next(err); check the documentation for the version you use.

JavaScript· A sensible order (Express, after npm install express)
import express from "express";
const app = express();

app.use(express.json());              // 1. parse bodies first
app.use((req, res, next) => {         // 2. cross-cutting checks
  if (!req.headers.authorization) return res.status(401).json({ error: "unauthorized" });
  next();
});

app.get("/health", (req, res) => res.json({ ok: true }));   // 3. routes

app.use((req, res) => res.status(404).json({ error: "not found" }));  // 4. fallback
app.use((err, req, res, next) => {    // 5. errors last
  console.error(err);
  res.status(500).json({ error: "server error" });
});

app.listen(3000);

13. What are the security basics for a Node API?

Validate every input with a schema library or your own checks and reject what does not fit, rather than trusting the client. Set protective response headers; the helmet package adds a common set in one call. Rate-limit login and other sensitive routes, for example with express-rate-limit, so password guessing is slow. Use parameterised queries to prevent injection, hash passwords with a slow algorithm such as bcrypt or argon2, and keep dependencies updated by running npm audit and reading its findings.

14. What does a middleware for rate limiting need to decide?

It needs a key, usually the client address or account, a window and a maximum count. Behind a proxy or load balancer the client address is the proxy's unless you configure Express to trust the proxy header, and doing that carelessly lets clients forge it. A limiter held in process memory resets on restart and is not shared across several instances, so multi-instance setups use a shared store.

Memory leaks and how to find them

15. What causes memory leaks in Node?

The usual causes are growing global collections such as an unbounded cache object, event listeners added on every request and never removed, closures that keep large objects reachable, and timers that are never cleared. Node warns when more than ten listeners are added to one emitter, and that warning is worth taking seriously. A leak is a steady climb in memory after garbage collection, not a high number at one moment.

16. How do you find one?

First confirm the trend by logging process.memoryUsage().heapUsed over time. Then take heap snapshots with the --inspect flag and Chrome DevTools, run some traffic, take another, and compare which object types grew and what retains them. Fix the retention, such as bounding the cache or removing the listener, then repeat the measurement to confirm the line goes flat.

JavaScript· A leak in six lines, and the measurement
const cache = {};
setInterval(() => {
  cache[Date.now()] = new Array(10000).fill("x");   // never removed
  const mb = process.memoryUsage().heapUsed / 1024 / 1024;
  console.log("heap MB:", mb.toFixed(1));
}, 200);
// Run it and watch the number rise; bound the cache or use a Map with a size limit to fix it.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.