Technology

Node.js Interview Questions and Answers

Node.js powers the backend of countless startups and product companies. These Node.js interview questions cover modules, npm and the event loop for freshers, then streams, error handling, clustering, worker threads, security, performance and scaling for experienced Node.js developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise Node.js questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Node.js Interview Questions with answers. Examples: What is Node.js, and why is it good for APIs? What is the difference between CommonJS and ES modules? What is package.json, and what is the difference between dependencies and devDependencies? Explain the Node.js event loop.
Node.js Interview Questions: 30 questions with model answers on this page.

Basic Node.js interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is Node.js, and why is it good for APIs?

Answer flow · 3 steps
  1. Node.js is a JavaScript runtime built on Chrome's V8 engine that runs JavaScript outside the browser.

  2. It uses a single-threaded event loop with non-blocking I/O, so one process can handle many concurrent connections while waiting on databases, files and networks.

  3. That makes it efficient for APIs, real-time apps and microservices, and lets teams use JavaScript on both frontend and backend.

2. What is the difference between CommonJS and ES modules?

Answer flow · 4 steps
  1. CommonJS uses require() and module.exports, loads modules synchronously and was Node's original system.

  2. ES modules use import and export, are the JavaScript standard, are loaded asynchronously and support top-level await and tree-shaking.

  3. Node uses ES modules for .mjs files or when package.json has "type": "module".

  4. New projects increasingly use ES modules.

3. What is package.json, and what is the difference between dependencies and devDependencies?

package.json describes a project: its name, scripts, version and the packages it depends on. dependencies are needed at runtime, such as express. devDependencies are only needed for development and building, such as testing tools and linters. package-lock.json records exact versions so every install is identical, and npm ci installs from it in CI.

4. What is the difference between npm and npx?

npm is Node's package manager: it installs packages listed in package.json, runs scripts with npm run, and publishes packages. npx runs a package's command without installing it globally, for example npx create-next-app, downloading it temporarily if needed. Alternatives to npm include pnpm, which saves disk space, and Yarn.

5. How is Node.js different from JavaScript in the browser?

Answer flow · 3 steps
  1. Both run JavaScript, but Node.js has no DOM, window or document.

  2. Instead it provides access to the file system, networking, processes and operating system through modules such as fs, http, path and os.

  3. Node.js controls its runtime version, so you can use modern features without worrying about browser support, and it uses modules and npm packages as its main way to organise code.

6. Which global objects does Node.js provide?

process (environment variables, arguments, exit codes and events), Buffer for binary data, console, timers (setTimeout, setInterval, setImmediate), globalThis, and in CommonJS modules __dirname, __filename, require and module. In ES modules, import.meta.dirname and import.meta.filename replace __dirname and __filename.

7. What is the difference between synchronous and asynchronous fs methods?

Answer flow · 3 steps
  1. Synchronous methods such as fs.readFileSync block the event loop until the file is read, so no other request can be handled meanwhile; they are acceptable in start-up scripts and CLI tools.

  2. Asynchronous methods, especially the promise versions in fs/promises with await, let Node.js keep serving other requests while the operating system reads the file.

  3. Servers should always use the asynchronous versions.

8. What is callback hell, and how do you avoid it?

Callback hell is deeply nested callbacks, where each asynchronous step is written inside the previous one, making code hard to read and error handling repetitive. It is avoided with promises and async/await, which make asynchronous code read top to bottom with try/catch, and by splitting logic into small named functions. util.promisify converts older callback APIs to promises.

9. What is a Buffer?

Answer flow · 4 steps
  1. A Buffer is a fixed-size chunk of raw binary data, used when working with files, network packets, images or encryption.

  2. It is similar to a Uint8Array.

  3. You create one with Buffer.from("text") or Buffer.alloc(size) and convert it back with toString("utf8") or toString("base64").

  4. Streams pass data around in Buffer chunks.

10. How do you manage configuration and environment variables?

Answer flow · 3 steps
  1. Configuration that changes between environments, such as database URLs and API keys, comes from environment variables read through process.env, never hard-coded or committed to Git.

  2. In development a .env file loaded with dotenv or Node's built-in --env-file flag is convenient.

  3. I validate required variables at start-up with a schema so the app fails fast if something is missing.

11. How do you create a basic HTTP server without a framework?

Use the built-in http module: http.createServer receives a request and a response object, you check req.method and req.url, set the status and headers, and end the response. Frameworks such as Express or Fastify add routing, body parsing and middleware on top of this.

import http from 'node:http';

http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ ok: true }));
  }
  res.writeHead(404).end();
}).listen(3000);

Intermediate Node.js interview questions

Applied problems, trade-offs and questions about your own projects.

12. Explain the Node.js event loop.

Answer flow · 3 steps
  1. The event loop runs callbacks in phases: timers (setTimeout and setInterval), pending callbacks, poll (waiting for and running I/O callbacks), check (setImmediate) and close callbacks.

  2. Between phases, Node runs process.nextTick callbacks first and then promise microtasks.

  3. Slow I/O is handled by the operating system or libuv's thread pool, so the main thread stays free as long as your own code does not block it.

13. How do you handle errors in Node.js?

Answer flow · 4 steps
  1. For async/await I use try/catch, and for promises .catch.

  2. In Express I pass errors to next(err) and have one central error-handling middleware that logs and returns a safe response.

  3. I distinguish operational errors, such as invalid input or a failed request, from programmer errors.

  4. Unhandled rejections and uncaught exceptions are logged, and the process is restarted cleanly by a process manager, because its state may be corrupt.

14. What are streams, and when would you use them?

Answer flow · 3 steps
  1. Streams process data in chunks instead of loading it all into memory.

  2. There are readable, writable, duplex and transform streams.

  3. I use them to read or upload large files, process big CSV exports, compress data on the fly or proxy responses. pipeline() connects streams and handles errors and backpressure, so a fast producer does not overwhelm a slow consumer.

15. How do you secure a Node.js API?

I validate all input with a schema library such as Zod or Joi, use parameterised queries or an ORM to prevent injection, hash passwords with bcrypt or argon2, and use short-lived tokens or secure HttpOnly cookies. I add security headers with helmet, configure CORS strictly, rate-limit endpoints, keep secrets in environment variables or a secrets manager, and run npm audit and keep dependencies updated.

16. What is the EventEmitter?

Answer flow · 3 steps
  1. EventEmitter, from the events module, implements the observer pattern: objects emit named events and listeners registered with on or once react to them.

  2. Many core modules, including streams, HTTP servers and child processes, are EventEmitters.

  3. Always listen for the error event, since an unhandled error event crashes the process, and remove listeners you no longer need to avoid leaks.

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

process.nextTick callbacks run immediately after the current operation, before the event loop continues and even before promise callbacks, so too many can starve I/O. setImmediate callbacks run in the check phase of the next event loop iteration, after I/O. Prefer setImmediate or queueMicrotask in most cases; nextTick is mainly used inside libraries.

18. What is libuv, and what is the thread pool?

libuv is the C library that gives Node.js its event loop and asynchronous I/O across operating systems. Network I/O uses the operating system's non-blocking mechanisms, but some tasks, such as file system operations, DNS lookups, compression and some crypto, run on libuv's thread pool, which has four threads by default and can be resized with UV_THREADPOOL_SIZE.

19. What is the difference between spawn, exec and fork?

All three in the child_process module start other processes. spawn launches a command and streams its output, which suits long-running processes and large output. exec runs a command in a shell and buffers the whole output, which suits short commands but is risky with user input because of shell injection. fork starts another Node.js script with a built-in messaging channel to the parent.

20. How do you handle file uploads in Node.js?

Answer flow · 3 steps
  1. Use middleware such as multer or busboy to parse multipart form data, streaming files to disk or directly to cloud storage such as S3 rather than holding them in memory.

  2. Limit file size and count, check the real file type rather than trusting the name, generate new file names, store files outside the web root, and scan them if users can share them.

  3. Pre-signed URLs let clients upload directly to storage.

21. How should you do logging in a Node.js application?

Answer flow · 3 steps
  1. Use a fast structured logger such as pino, writing JSON logs with levels (debug, info, warn, error), timestamps and context such as request ID and user ID, so a log platform can search and filter them.

  2. Never log passwords, tokens or personal data.

  3. Avoid console.log in production code, and add request logging and correlation IDs to trace a request across services.

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

Answer flow · 3 steps
  1. Listen for SIGTERM and SIGINT, which platforms such as Kubernetes and Docker send before stopping a container.

  2. On the signal, stop accepting new connections with server.close(), let in-flight requests finish, close database connections and queues, then exit, with a timeout that forces exit if cleanup hangs.

  3. Health checks should start failing first so the load balancer stops sending traffic.

High level Node.js interview questions

System design, deep internals, leadership and tough follow-ups.

23. How do you scale a Node.js application?

Answer flow · 3 steps
  1. Node runs JavaScript on one core per process, so I run multiple processes, using the cluster module or PM2, or more commonly multiple containers behind a load balancer.

  2. The app must be stateless, with sessions and caches in Redis.

  3. I add caching, move slow work to background queues such as BullMQ, use database connection pooling, and scale horizontally based on metrics.

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

The cluster module starts multiple Node processes that share a server port, each with its own memory and event loop, which helps handle more requests across CPU cores. Worker threads run JavaScript in parallel threads within one process and can share memory with SharedArrayBuffer, which suits CPU-heavy tasks such as image processing or parsing, so they do not block the main event loop.

25. How do you find and fix a memory leak or performance problem in Node.js?

Answer flow · 3 steps
  1. I monitor memory and event loop lag in production.

  2. To investigate I reproduce under load, take heap snapshots with --inspect and Chrome DevTools or heapdump, and compare them to find objects that keep growing, often global caches, listeners that are never removed or closures.

  3. For CPU problems I use a CPU profile or clinic.js flame graphs to find hot functions, then fix and verify with a load test.

26. How do you build real-time features in Node.js?

Answer flow · 3 steps
  1. Use WebSockets, through the ws library or Socket.IO, which adds rooms, automatic reconnection and fallbacks, for chat, live notifications and collaboration.

  2. Server-Sent Events are simpler for one-way updates such as live scores.

  3. To scale across several servers, share messages through Redis pub/sub or the Socket.IO Redis adapter, and use sticky sessions where required.

27. How do you add caching with Redis in a Node.js API?

Answer flow · 3 steps
  1. Use the cache-aside pattern: check Redis for a key first, return it if found, otherwise load from the database, store the result with an expiry and return it.

  2. Invalidate or update the key when the data changes.

  3. Cache only data that tolerates being slightly stale, choose clear key names, protect against stampedes when a popular key expires, and monitor hit rate.

28. What makes a well-designed REST API in Node.js?

Resource-based URLs with correct HTTP methods and status codes, input validation on every endpoint, consistent JSON error responses, pagination, filtering and sorting for lists, versioning such as /v1, authentication and authorisation, rate limiting, idempotency keys for payments, and documentation with OpenAPI. Internally, thin controllers call services, and services call data access code.

29. How do you test a Node.js backend?

Answer flow · 3 steps
  1. Unit tests for business logic with Vitest, Jest or the built-in node:test runner; integration tests that call real HTTP endpoints with Supertest against a test database started with Docker or Testcontainers; and contract or end-to-end tests for critical flows.

  2. External services are mocked at the network level with nock or MSW.

  3. Tests run in CI on every pull request.

30. What modern Node.js features have you used?

Built-in fetch and Web Streams, the node:test test runner, --watch mode, --env-file for environment variables, native TypeScript type stripping so .ts files can run directly, require() of ES modules, the permission model to restrict file and network access, and stable worker threads and AbortController. Using even-numbered LTS releases in production is the safe choice.

Node.js machine coding round questions

Tasks you build live in 30 to 60 minutes. What interviewers look for, plus a compact solution to compare with yours.

Read a very large file line by line without running out of memory.

Tests streams. Reading the whole file with readFile would load gigabytes into memory; readline over a read stream processes one line at a time.

import { createReadStream } from 'node:fs';
import readline from 'node:readline';

async function countErrors(path) {
  const lines = readline.createInterface({ input: createReadStream(path), crlfDelay: Infinity });
  let errors = 0;
  for await (const line of lines) {
    if (line.includes('ERROR')) errors++;
  }
  return errors;
}

Run async tasks with a concurrency limit.

A favourite intermediate question. Start up to limit tasks, and each time one finishes start the next, keeping results in the original order.

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

// await mapLimit(urls, 5, (url) => fetch(url).then((r) => r.status));
Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a backend developer interview?

See all Backend Developer interview questions, covering Node.js, Express.js, NestJS, Python, Django and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields