Rates TodayNIFTY25,670-0.83%SENSEX83,630.7-0.83%Gold 24K ₹11,320.24/g down186.46Silver ₹134.77/g down2.72
InsightforGeeks

Node.js interview questions and answers

27 questions · Easy, Medium and Hard

These are the Node.js questions that come up most in interviews, with answers short enough to say out loud. They run from the basics to the questions that separate people who have run Node.js in production from those who have only read about it.

Use each answer as a starting point, then try it yourself in code. Interviewers care more about whether you understand why something works than about the exact wording.

Easy 9Medium 11Hard 7

Easy questions

What is Node.js?

Node.js is a runtime that lets you run JavaScript outside the browser. It is built on Chrome's V8 engine and uses an event-driven, non-blocking I/O model, which makes it well suited to servers that handle many connections at once, such as APIs and real-time apps.

Your JavaScript runs on a single main thread, but the work of waiting for files, networks and databases is handed to the system, so the thread is free to handle other requests meanwhile.

Often asked next: Is Node.js a good choice for CPU-heavy work?

What is the difference between Node.js and JavaScript in the browser?

Both run JavaScript, but the environment around it differs. The browser gives you the DOM, window and Web APIs such as fetch and localStorage. Node.js has no DOM, but gives you modules for the file system (fs), networking (http), process, streams and more.

Modern Node.js also has fetch, but code written for one environment often needs changes to run in the other.

What are npm and package.json?

npm is Node's package manager and the registry of packages you can install. package.json describes your project: its name, version, scripts, and the packages it depends on. package-lock.json records the exact versions installed so every machine gets the same tree.

Commands such as npm install, npm run <script> and npm ci (a clean install from the lock file, used in CI) are worth knowing.

Often asked next: What is the difference between dependencies and devDependencies?

What is the difference between dependencies and devDependencies?

dependencies are packages your app needs to run in production, such as Express. devDependencies are only needed while developing, such as a test runner, linter or TypeScript compiler. Installing with npm install --omit=dev skips the dev ones on a server.

What is the difference between CommonJS and ES modules?

CommonJS is Node's original system: require() to load and module.exports to export. It loads synchronously. ES modules use import and export, load asynchronously, and are the standard that browsers also use.

Node treats a file as an ES module when it ends in .mjs or when "type": "module" is set in package.json. ES modules have no __dirname or require by default.

// CommonJS
const fs = require('fs');
module.exports = { run };

// ES module
import fs from 'fs';
export function run() {}

What is a callback, and what is callback hell?

A callback is a function passed to another function to be called when work finishes. Node's older APIs use the error-first style: callback(err, result).

Callback hell is deeply nested callbacks that are hard to read and handle errors in. Promises and async/await fix it by letting you write asynchronous code that reads from top to bottom.

import { readFile } from 'node:fs/promises';

async function load() {
  try {
    const text = await readFile('data.json', 'utf8');
    return JSON.parse(text);
  } catch (err) {
    console.error('Could not load data', err);
  }
}

How do you use environment variables in Node.js?

Read them from process.env, for example process.env.PORT. Keep secrets such as database passwords and API keys out of your code and out of Git; load them from the environment or from a .env file that is ignored by Git.

Node 20.6 and later can load a file with node --env-file=.env app.js. Before that, the dotenv package was the usual way.

Env file validator →

What is middleware in Express?

Middleware is a function with the signature (req, res, next) that runs between receiving a request and sending the response. It can read or change the request, end the response, or call next() to pass control on. Logging, parsing JSON bodies, authentication and CORS are all middleware.

Order matters: middleware runs in the order you register it.

app.use(express.json());

app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();
});

How do you handle errors in Express?

Express recognises error-handling middleware by its four arguments, (err, req, res, next). Register it after your routes, and send a response from it so every error is handled in one place.

In Express 4, an error thrown inside an async route is not caught automatically, so you must call next(err) or wrap the handler. Express 5 passes rejected promises to the error handler for you.

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: 'Something went wrong' });
});

Medium questions

Explain the Node.js event loop.

The event loop is what lets Node.js do many things with one thread. It repeatedly cycles through phases: timers (setTimeout, setInterval), pending callbacks, poll (waiting for and running I/O callbacks), check (setImmediate) and close callbacks.

Between steps, Node runs the microtask queues: process.nextTick callbacks first, then resolved promise callbacks. Long synchronous code blocks the loop, so nothing else runs until it finishes.

Often asked next: What happens if you run a heavy loop inside a request handler?

What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?

process.nextTick runs its callback right after the current operation, before the event loop continues, and before promise callbacks. setImmediate runs in the check phase, after the poll phase. setTimeout(fn, 0) runs in the timers phase after at least the minimum delay.

Inside an I/O callback, setImmediate always runs before setTimeout(fn, 0). From the main module the order of those two is not guaranteed. Overusing nextTick can starve I/O.

What is the difference between blocking and non-blocking code, and how do you avoid blocking the event loop?

Blocking code, such as fs.readFileSync, a big JSON parse or a CPU-heavy loop, stops the single thread until it finishes, so every other request waits. Non-blocking code starts the work and returns, then runs a callback or resolves a promise when done.

To avoid blocking: use the asynchronous versions of APIs, break large jobs into chunks, move CPU-heavy work to worker_threads or a separate service, and use streams for large files.

What are streams in Node.js, and why use them?

Streams process data piece by piece instead of loading it all into memory. There are four kinds: Readable, Writable, Duplex (both) and Transform (changes data as it passes through). They keep memory use low for large files and let you start sending a response before all the data is ready.

Use stream.pipeline to connect streams: it forwards errors and cleans up properly. Streams also handle backpressure, which means a fast reader does not overwhelm a slow writer.

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';

await pipeline(
  createReadStream('big.log'),
  createGzip(),
  createWriteStream('big.log.gz')
);

What is a Buffer?

A Buffer is a fixed-size chunk of raw binary data, used when working with files, network packets, images and encodings. It is a subclass of Uint8Array. You can create one from a string with Buffer.from('hello'), and turn it back with buf.toString('utf8'). It is also how you convert to and from Base64 or hex.

Base64 encoder and decoder →

What is EventEmitter?

EventEmitter is the class behind much of Node's design. An object can emit named events with emit() and other code reacts with on() or once(). Streams, HTTP servers and process are all event emitters.

Remember to remove listeners you no longer need with off(). Forgotten listeners are a common source of memory leaks, and Node warns when an emitter has more than ten for one event.

import { EventEmitter } from 'node:events';

const bus = new EventEmitter();
bus.on('order', (id) => console.log('new order', id));
bus.emit('order', 42);

What is the difference between Promise.all, Promise.allSettled and Promise.race?

Promise.all waits for every promise and rejects as soon as one rejects. Promise.allSettled always waits for all of them and tells you which succeeded and which failed. Promise.race settles with the first promise to finish, whether it succeeded or failed.

Use all when you need everything to succeed, allSettled when partial results are acceptable, and race for patterns such as a timeout.

How do you secure an Express API?

Layer several protections: validate and sanitise all input; hash passwords with bcrypt or argon2; use parameterised queries to prevent SQL injection; set security headers with helmet; add rate limiting; configure CORS to allow only the origins you trust; serve everything over HTTPS; and keep dependencies updated.

Keep secrets in environment variables, never log tokens or passwords, and return generic error messages to clients.

Often asked next: How would you protect a login endpoint from brute-force attacks?

Node.js security guides →

What is the difference between JWT and session-based authentication?

With sessions, the server stores the session data and gives the browser a session ID in a cookie. It is easy to revoke, but the server must keep state. With JWT, the token itself carries signed claims, so the server can verify it without a lookup, which suits several services and mobile apps. But a JWT is hard to revoke before it expires.

Whichever you use, store tokens in secure, HttpOnly cookies where possible, keep access tokens short-lived, and never put secrets in the token payload because it is only encoded, not encrypted.

JWT decoder →

How do you handle uncaught exceptions and unhandled promise rejections?

Since Node 15, an unhandled promise rejection crashes the process by default. Attach a .catch or use try/catch with await so errors are handled where they happen. You can listen for unhandledRejection and uncaughtException to log the error, but after an uncaught exception the process may be in an unknown state, so log it and exit, and let a process manager such as pm2 or systemd restart it.

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection', reason);
  process.exit(1);
});

What does REST mean, and what is an idempotent method?

REST is a style of designing APIs around resources, using HTTP methods and status codes: GET to read, POST to create, PUT or PATCH to update, DELETE to remove. A method is idempotent if repeating the same request leaves the server in the same state as doing it once. GET, PUT and DELETE are idempotent; POST is not. Idempotency matters for safe retries.

Hard questions

How can Node.js handle many concurrent requests with a single thread?

The main thread runs your JavaScript, but it does not wait for slow operations. Network I/O is handled by the operating system, and libuv, the library under Node, uses a thread pool (four threads by default, set with UV_THREADPOOL_SIZE) for file system work, DNS lookups, crypto and compression.

While those run, the event loop is free to take new requests. When they finish, their callbacks are queued and run on the main thread. This is why Node handles many I/O-bound connections well but struggles when a request needs long CPU work.

Often asked next: How would you handle a request that needs heavy computation?

What is the difference between the cluster module and worker threads?

cluster starts several Node.js processes that share one server port, so you can use every CPU core for handling requests. Each worker has its own memory. worker_threads runs extra threads inside one process, which can share memory with SharedArrayBuffer, and is meant for CPU-heavy tasks, not for serving more connections.

In practice, many teams run several instances with pm2 or containers behind a load balancer instead of using cluster directly.

How would you scale a Node.js application?

First make the app stateless, so any instance can serve any request: keep sessions and uploads in Redis or object storage, not in memory or on local disk. Then run several instances behind a load balancer, using pm2, containers or an orchestrator.

Add caching (Redis, HTTP caching, a CDN), use database connection pooling and indexes, move slow work to a queue with background workers, and measure before optimising so you fix real bottlenecks.

Often asked next: How would you scale WebSocket connections?

How do you find and fix a memory leak in Node.js?

Typical causes are global variables that keep growing, unbounded in-memory caches, closures holding on to large objects, and event listeners or timers that are never removed.

To find one, watch process.memoryUsage() over time, run with --inspect and take heap snapshots in Chrome DevTools at different times, and compare which objects are growing. Fix it by bounding caches (for example with an LRU cache), removing listeners, and clearing timers.

How do you shut down a Node.js server gracefully?

Listen for SIGTERM (sent by pm2, Docker and Kubernetes) and SIGINT. Stop accepting new connections with server.close(), let in-flight requests finish, close database connections, then exit. Add a timeout so a stuck request cannot keep the process alive forever.

process.on('SIGTERM', () => {
  server.close(async () => {
    await db.close();
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 10000).unref();
});

How would you implement rate limiting?

The simplest option is a middleware such as express-rate-limit, which counts requests per client (usually per IP or API key) in a time window. With several instances, the counters must live in a shared store such as Redis, otherwise each instance counts separately.

Common algorithms are fixed window, sliding window and token bucket. Return status 429 with a Retry-After header. Behind a proxy or CDN, make sure you read the real client IP, not the proxy's.

How do you design a reliable background job system in Node.js?

Put jobs in a queue such as BullMQ (backed by Redis) or a managed queue like SQS, and process them in separate worker processes. Make jobs idempotent so a retry does not repeat side effects, set retry with backoff, add a dead-letter queue for jobs that keep failing, and monitor queue length and failures.

Cron expression generator →

Practise in code

Interviews often include a short coding task. These challenges run in your browser.

Keep learning

Handy free tools

More interview questions