100 Node.js Developer Interview Questions With Answers

A hundred Node.js questions with short answers and code. They cover the event loop, streams, APIs, security and Node 26.

Smiling back-end developer writing Node.js server code on a laptop
Photo: Pexels

Node.js is a runtime that runs JavaScript outside the browser, mostly on servers. It uses Google’s V8 engine and a library called libuv to handle files, network calls and timers without blocking. So one Node process can serve thousands of open connections, which is why teams use it for APIs, real-time apps and tooling.

Node.js developer interview questions test how well you understand that non-blocking model. Expect questions on the event loop first, then on modules, async code, streams and building APIs with Express or Fastify. Senior rounds add security, scaling with worker threads or clusters, and debugging memory leaks in production.

This post covers 100 such questions in that order, each with a short answer and code where it helps. After the questions, it walks through a typical Node.js coding task and answers a few common questions about the interview itself.

Back-end developer running a Node.js server in a terminal on a laptop
Photo: Pexels

Node.js Versions to Know Before the Interview

Interviewers often ask which Node version you run and why. The short answer is that production apps should run an LTS line. Also, the Node.js release schedule is changing. From Node.js 27 on, Node ships one major release a year, and every major becomes LTS.

So the old rule that only even numbers get LTS stops with Node 26. The table shows the lines you will see in job posts and codebases.

VersionCodenameFirst releasedRelease status
Node 22JodApril 24, 2024LTS
Node 24KryptonMay 6 of last yearLTS
Node 25NoneOctober 15 of last yearEnd of life
Node 26LithiumMay 5, 2026Latest LTS
Node 27NoneOctober 29, 2026Alpha

Node 20 (Iron) is now end of life, so an app still on it needs an upgrade plan.

Node.js Core and Event Loop Questions

1. What is Node.js?

Node.js is an open-source JavaScript runtime built on the V8 engine. It lets you run JavaScript on servers and command lines. It uses an event-driven, non-blocking I/O model, so it handles many connections with one main thread.

2. Is Node.js single-threaded?

Your JavaScript runs on one main thread. However, Node uses a libuv thread pool for some tasks, such as reading files, DNS lookups and heavy crypto. You can also create more threads with worker_threads. So the code you write is single-threaded, but Node itself is not.

3. What is the event loop?

The event loop is the cycle that lets Node run callbacks when async work finishes. While the main thread is free, the loop picks ready callbacks from its queues and runs them one by one. If one callback runs for a long time, everything else waits.

4. What are the phases of the event loop?

The phases are timers, pending callbacks, idle and prepare, poll, check and close callbacks. Timers run setTimeout and setInterval callbacks, poll waits for I/O, and check runs setImmediate callbacks. Between each callback, Node drains the nextTick queue and the promise microtask queue.

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

process.nextTick runs its callback right after the current operation, before promise callbacks and before the loop moves on. setImmediate runs in the check phase of the next loop turn. So too many nextTick calls can starve I/O.

6. What prints first: setTimeout 0 or setImmediate?

From the main module, the order is not fixed, because it depends on how fast the loop starts. Inside an I/O callback, setImmediate always runs first. That is a common trick question.

7. What is libuv?

libuv is the C library under Node that provides the event loop, the thread pool and cross-platform async I/O. On Linux it uses epoll, and on macOS it uses kqueue. The default thread pool has 4 threads, set by UV_THREADPOOL_SIZE.

8. What blocks the event loop?

Long synchronous work blocks it, such as big JSON parsing, sync calls like readFileSync in a request, heavy loops and some regex patterns. While it runs, no other request is served. Move such work to a worker thread or split it into chunks.

9. What is non-blocking I/O?

Non-blocking I/O means Node starts a read or a network call and moves on, instead of waiting. When the result is ready, a callback or promise runs. As a result, one process can handle thousands of slow clients.

10. When is Node.js a poor choice?

Node is a poor choice for long CPU-heavy work on the main thread, such as video encoding or large number crunching. You can still use worker threads, but Go, Rust or Java may serve that load better. Node fits I/O-heavy APIs and real-time apps well.

11. What is V8?

V8 is Google’s JavaScript and WebAssembly engine, also used in Chrome. It compiles JavaScript to machine code with a just-in-time compiler. Node updates V8 with each major release, which brings new JavaScript features.

12. What are global objects in Node?

Common globals include globalThis, process, Buffer, console, setTimeout, URL, fetch and structuredClone. In CommonJS files, require, module, exports, __dirname and __filename also exist. In ES modules, use import.meta.dirname and import.meta.filename.

13. What is the process object?

process gives you information and control over the running Node process. For example, process.env holds environment variables, process.argv holds command-line arguments, and process.exit() ends the process. It also emits events like exit and SIGTERM.

14. What is an EventEmitter?

EventEmitter from node:events lets objects emit named events and register listeners with on. Streams, HTTP servers and sockets all extend it. For example, server.on('request', handler).

15. What happens if an EventEmitter emits ‘error’ with no listener?

Node throws the error, and if nothing catches it, the process crashes. So always add an error listener to streams, sockets and custom emitters. This is one of the most common causes of surprise crashes.

16. What is the REPL?

REPL stands for read, eval, print, loop. You start it by running node with no file. It is handy for testing a quick expression or checking how a built-in module behaves.

17. How do you read command-line arguments?

Use process.argv, where the first two items are the Node path and the script path. For real CLIs, use util.parseArgs from Node core or a library like Commander. For example, node app.js --port 8080.

18. What is the difference between Node.js and a browser runtime?

Both run JavaScript on V8 or a similar engine. However, Node has file system, process and network modules, and no DOM or window. Browsers sandbox code, while Node code can touch the whole machine unless you use the permission model.

19. What is the Node.js permission model?

The permission model limits what a process can access. Start Node with --permission, then grant access with flags such as --allow-fs-read, --allow-fs-write, --allow-net and --allow-child-process. It has been stable since Node 22.13 and 23.5.

20. How do you check a permission at runtime?

Call process.permission.has('fs.write', '/data'). It returns true or false. This works only when the process runs with the permission model turned on.

Modules and npm Questions

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

CommonJS uses require and module.exports and loads modules synchronously. ES modules use import and export, load asynchronously and support top-level await. Node treats .mjs files and packages with "type": "module" as ES modules.

22. Can you require an ES module?

Yes, in current versions. require() of an ES module is on by default since Node 22.12, 20.19 and 23.0, as long as the module has no top-level await. Before that, you had to use dynamic import().

23. What does module.exports do compared with exports?

exports starts as a reference to module.exports. Adding properties to either works. However, assigning a new value to exports breaks the link, so use module.exports = fn when you export a single function.

24. How does require resolve a module?

Node checks core modules first, then relative paths like ./util, then node_modules folders from the current directory up to the root. It also reads the exports and main fields in package.json. Results are cached after the first load.

25. What is module caching?

After a module loads once, require returns the same object every time. So a module works like a singleton. If you need fresh state, export a factory function.

26. What is the node: prefix?

import fs from 'node:fs' shows that you want a core module, not an npm package with the same name. Some newer modules, such as node:test and node:sqlite, work only with the prefix.

27. What is the difference between dependencies and devDependencies?

dependencies are needed at runtime, such as Express. devDependencies are needed only to build or test, such as Vitest or ESLint. In production, npm ci --omit=dev skips dev packages.

28. What do ^ and ~ mean in package.json?

^1.4.2 allows updates that do not change the major number, so up to 1.x.x. ~1.4.2 allows only patch updates, so up to 1.4.x. The lock file pins exact versions for repeatable installs.

29. What is the difference between npm install and npm ci?

npm install can update the lock file. npm ci installs the exact versions in the lock file and deletes node_modules first. It also fails if the lock and package.json disagree. So use npm ci in CI and Docker builds.

30. What are peerDependencies?

peerDependencies say which version of another package your package expects the app to install. Plugins use them, for example an ESLint plugin that needs ESLint. Since npm 7, npm installs peers automatically and fails on conflicts.

31. What does node –run do?

node --run build runs a script from package.json without starting npm. It was added in Node 22 as an experimental flag. Since Node 26.9, running node --run with no name lists the scripts.

32. What is npx?

npx runs a package’s binary without a global install. For example, npx create-vite@latest downloads and runs the tool once. It also runs binaries already in your local node_modules.

Read also: 200 Angular Interview Questions With Short Answers

Async JavaScript Questions in Node.js

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

Callback hell is deep nesting of callbacks, which makes code hard to read and to handle errors in. Avoid it with Promise chains and async/await. Also, most core modules now offer a Promise-based API next to the callback one.

34. What is the error-first callback pattern?

Node callbacks take an error as the first argument and the result second: fs.readFile(p, (err, data) => {...}). If err is set, handle it and return. This was the standard before Promise support arrived.

35. How do you turn a callback API into a promise?

Use util.promisify(fn). For example, const sleep = util.promisify(setTimeout). Many core modules already ship Promise-based versions, such as the timers and DNS modules.

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

Promise.all rejects as soon as one promise fails. allSettled waits for all and reports each result. race settles with the first to settle, and any resolves with the first success.

37. How do you run async tasks with a limit on concurrency?

Process them in batches, or use a small pool that keeps, say, five requests in flight. Libraries like p-limit do this. Without a limit, Promise.all over 10,000 URLs can exhaust sockets or hit rate limits.

38. What happens to an unhandled promise rejection?

Since Node 15, an unhandled rejection crashes the process by default. You can listen to process.on('unhandledRejection') for logging. However, the real fix is to await or catch every promise.

39. Should you catch uncaughtException and keep running?

No. After an uncaught exception, the app can be in a broken state. Log the error, close connections and exit, then let a process manager or Kubernetes restart it.

40. What is top-level await?

In ES modules, you can use await outside an async function, such as const config = await loadConfig(). The module that imports it waits until it finishes. It does not work in CommonJS.

41. What is AsyncLocalStorage?

AsyncLocalStorage from node:async_hooks keeps data across an async call chain, like a request ID. You call als.run(store, fn), and any code inside can read als.getStore(). Logging libraries use it to tag every log line with the request.

42. How do you cancel an async operation?

Pass an AbortSignal. For example, fetch(url, { signal: AbortSignal.timeout(5000) }) stops after five seconds. Many core APIs, such as fs.readFile and the Promise-based setTimeout, accept a signal too.

43. What is the difference between async iteration and events?

With events, data is pushed to you through listeners. With async iteration, you pull data with for await (const chunk of stream). Async iteration handles backpressure for you and makes errors easier to catch.

44. How do you sleep in async code?

Import the Promise-based setTimeout from the timers module, then call await setTimeout(1000). It returns a promise that resolves after the delay. Never use a busy loop, because it blocks the event loop.

45. What is the difference between microtasks and macrotasks?

Microtasks are promise callbacks and queueMicrotask jobs, and they run right after the current task. Macrotasks include timers, I/O callbacks and setImmediate. Node runs all pending microtasks before moving to the next macrotask.

Streams, Buffers and File System Questions

46. What is a stream?

A stream processes data in pieces instead of loading it all into memory. There are four types: Readable, Writable, Duplex and Transform. For example, you can send a 2 GB file to a client with a fixed, small amount of memory.

47. What is backpressure?

Backpressure happens when a writable stream cannot take data as fast as a readable one sends it. write() returns false, and you should wait for the drain event. pipe() and pipeline() handle this for you.

48. Why use stream.pipeline instead of pipe?

The Promise-based pipeline function connects streams, forwards errors and destroys all streams when one fails. With plain .pipe(), an error in one stream can leave others open and leak file handles. So pipeline is the safer default.

49. Write code to gzip a file with streams.

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
await pipeline(createReadStream('in.log'), createGzip(), createWriteStream('in.log.gz'));

50. What is a Buffer?

A Buffer is a fixed-size chunk of raw bytes. Node uses it for file data, network packets and binary formats. For example, Buffer.from('hi', 'utf8') creates two bytes, and buf.toString('base64') encodes them.

51. What is the difference between Buffer and a string?

A string holds text as characters. A Buffer holds raw bytes, which may or may not be text. So reading an image as a string corrupts it, while a Buffer keeps every byte.

52. What is the difference between readFile and createReadStream?

readFile loads the whole file into memory before you get it. createReadStream gives you chunks as they arrive. Use streams for large files or when you send data straight to a response.

53. Why avoid sync fs methods in a server?

readFileSync and friends block the event loop until the disk returns. In a request handler, that stops every other request. However, sync calls are fine at startup, for example to load a config file once.

54. How do you watch a file for changes?

Use fs.watch, or the Promise-based watch, which returns an async iterator of change events. Behaviour differs a little between Linux, macOS and Windows. Tools like chokidar smooth over those differences.

55. How do you build a file path safely?

Use path.join or path.resolve from node:path, not string concatenation. They handle slashes on every OS. Also check that a user-supplied path stays inside your base folder, to block ../ tricks.

56. What is a Transform stream?

A Transform stream changes data as it passes through, like compression, encryption or CSV parsing. You implement transform(chunk, encoding, callback). zlib.createGzip() is a built-in example.

57. What is object mode in streams?

By default, streams carry Buffers or strings. In object mode, they carry any JavaScript value, such as parsed rows. Set objectMode: true when you create the stream.

58. How do you read a large file line by line?

Use readline with a file stream:

const rl = readline.createInterface({ input: fs.createReadStream('big.csv') });
for await (const line of rl) { /* handle line */ }

Memory stays low even for a file of several gigabytes.

HTTP, Express and API Questions

59. How do you create an HTTP server without a framework?

import http from 'node:http';
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ ok: true }));
}).listen(3000);

Frameworks add routing, body parsing and middleware on top of this.

60. What is Express?

Express is a minimal web framework for Node. It adds routing, middleware and helpers like res.json(). Express 5 is the current major line and the default on npm. Its router catches a rejected promise from async middleware and treats it like a call to next(err), so the error handler gets it.

61. What is middleware in Express?

Middleware is a function with (req, res, next) that runs during a request. It can change the request, end the response or call next() to pass control on. Logging, auth checks and body parsing are typical examples.

62. How do you write an error-handling middleware?

Give it four arguments: (err, req, res, next). Express calls it when a handler throws or calls next(err). Register it after all routes, and send a safe message to the client while logging the full error.

63. What is the difference between app.use and app.get?

app.use mounts middleware for all methods on a path prefix. app.get handles only GET requests on an exact route pattern. For example, app.use('/api', auth) protects every API route.

64. How does Fastify differ from Express?

Fastify focuses on speed and has built-in JSON schema validation and serialization. It uses a plugin system with scoped plugins and has first-class async support. Teams pick it for high-traffic APIs, while Express has the larger ecosystem.

65. What is NestJS?

NestJS is a framework for building structured Node back ends with TypeScript. It uses modules, controllers, providers and dependency injection, much like Angular. It runs on Express by default and can switch to Fastify.

66. What is the difference between REST and GraphQL?

REST exposes resources at URLs with HTTP verbs, like GET /orders/5. GraphQL exposes one endpoint where clients ask for exactly the fields they need. GraphQL reduces over-fetching but needs extra care for caching and query cost.

67. How do you validate request bodies?

Validate at the edge with a schema library such as Zod, Joi or Fastify’s JSON schemas. Reject bad input with a 400 status and a plain error message. Never trust client data, even from your own front end.

68. How do you implement pagination in an API?

Offset pagination uses ?page=3&limit=20 and is easy to build. Cursor pagination uses ?after=<lastId> and stays fast and stable on large, changing tables. Return the next cursor in the response.

69. How do you make HTTP requests from Node?

Use the global fetch, which has been stable since Node 21. For more control, use undici, which powers fetch inside Node. Older code often uses axios or the http module.

70. What is CORS, and how do you handle it in Node?

CORS is a browser rule that blocks cross-origin requests unless the server allows them with headers like Access-Control-Allow-Origin. In Express, the cors middleware sets these. Allow only the origins you trust, not *, when cookies are involved.

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

Use WebSockets with a library like ws or Socket.IO, or Server-Sent Events for one-way updates. Also, Node 22 turned on its built-in, browser-style WebSocket client by default. For many servers, share messages through Redis pub/sub.

72. How do you upload files in Express?

Use middleware such as multer or busboy, which stream multipart data. Set file size and type limits. For large files, stream straight to cloud storage like S3 instead of saving to the server disk.

Node.js Security Questions

73. How do you store passwords?

Hash them with a slow, salted algorithm like bcrypt, scrypt or Argon2. Node’s crypto.scrypt works without extra packages. Never store plain or fast-hashed passwords such as MD5.

74. How do you prevent SQL injection?

Use parameterized queries or an ORM that does so, for example db.query('SELECT * FROM users WHERE id = $1', [id]). Never build SQL by joining strings with user input. The same idea applies to NoSQL queries.

75. What is JWT, and what are its risks?

A JSON Web Token is a signed token that carries data such as a user ID. So servers can check it without a session store. However, tokens are hard to revoke before expiry. Keep them short-lived, use refresh tokens, and store them in httpOnly cookies, not localStorage. For login options beyond passwords, see these passwordless authentication tools.

76. What does the helmet package do?

Helmet sets security-related HTTP headers in Express, such as Content-Security-Policy, Strict-Transport-Security and X-Content-Type-Options. It blocks a range of common browser attacks with one line. You can tune each header.

77. How do you add rate limiting?

Use middleware like express-rate-limit, or do it at the gateway or load balancer. Store counters in Redis when you run many instances. Return status 429 with a Retry-After header.

78. How do you keep secrets out of code?

Load them from environment variables or a secrets manager. Node can read a .env file with --env-file=.env, a flag that is no longer experimental since Node 24.10 and 22.21. Never commit the .env file to Git.

79. How do you check dependencies for known flaws?

Run npm audit in CI and update packages often. Also use lock files, review new packages before adding them, and turn on alerts from tools like Dependabot. Supply-chain attacks on npm packages are a real risk.

80. What is prototype pollution?

Prototype pollution is when an attacker sets properties like __proto__ in input that your code merges into objects. Then every object gets the injected property. Fix it by validating input, using Object.create(null) maps or Map, and updating merge libraries.

81. What is ReDoS?

ReDoS is a denial of service caused by a regex that takes a very long time on certain input. Since the regex runs on the main thread, one request can freeze the server. Avoid nested quantifiers and test regexes with long inputs.

82. How do you run untrusted code in Node?

You should not run it in the main process. The vm module is not a security sandbox. Use a separate container or a locked-down process, and consider the permission model to limit file and network access.

Performance, Scaling and Debugging Questions

83. How do you use all CPU cores?

Run several Node processes, one per core, with the cluster module, PM2 or several containers behind a load balancer. Each process has its own event loop and memory. Share state through a database or Redis.

84. What is the difference between cluster and worker_threads?

cluster forks separate processes that share a server port. worker_threads runs threads inside one process that can share memory with SharedArrayBuffer. Use cluster to scale HTTP traffic and workers for CPU-heavy jobs.

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

spawn starts a process and streams its output. exec runs a command in a shell and buffers the output. execFile skips the shell, which is safer, and fork starts a new Node process with a message channel.

86. How do you find a memory leak?

Take heap snapshots with --inspect and Chrome DevTools, or with v8.writeHeapSnapshot(), then compare them over time. Look for objects that keep growing, such as caches with no limit or listeners never removed. Also watch process.memoryUsage() in your metrics.

87. How do you profile CPU usage?

Run node --cpu-prof app.js to write a .cpuprofile file, then open it in Chrome DevTools. You can also attach DevTools live with --inspect. Flame graphs show which functions use the most time.

88. How do you raise the memory limit?

Use --max-old-space-size=4096 to give the V8 heap about 4 GB. Do this only after checking for leaks. In containers, keep it lower than the container’s memory limit.

89. What is a graceful shutdown?

On SIGTERM, stop accepting new requests with server.close(), finish the ones in flight, close database pools, then exit. Kubernetes sends SIGTERM before it kills a pod. Without this, users see failed requests during each deploy.

90. How do you cache in a Node API?

Cache in memory with an LRU for small, per-instance data. Use Redis for shared caches across instances. Also set HTTP cache headers like Cache-Control and ETag so browsers and CDNs can help.

91. How do you debug a Node app?

Start it with node --inspect app.js and open chrome://inspect, or use the VS Code debugger. Set breakpoints and step through. For production, rely on structured logs and traces instead.

92. What logging approach works in production?

Use a structured logger like Pino that writes JSON to stdout. Add a request ID to each line with AsyncLocalStorage. Then ship logs to a central tool and search by that ID.

Testing, TypeScript and Tooling Questions

93. What is the built-in test runner?

node:test is Node’s own test runner, stable since Node 20. You write test('adds', () => { assert.equal(add(1, 2), 3); }) and run node --test. It supports mocks, watch mode and coverage.

94. Can Node run TypeScript directly?

Yes. Node runs .ts files by stripping out the type annotations. Type stripping is on by default since Node 22.18 and 23.6, and stable since 24.12 and 25.2. It does not type-check, and it ignores tsconfig.json. So you still run tsc --noEmit in CI.

95. Which TypeScript features does type stripping not support?

Features that need code generation fail, such as enum declarations, namespaces with runtime code, parameter properties and import aliases. Also, .tsx files are not supported. Node 26 removed the --experimental-transform-types flag that used to handle some of these.

96. What does –watch do?

node --watch app.js restarts the process when the file or its imports change. It replaced nodemon for many teams. Use --watch-path to watch specific folders.

97. How do you test an Express route?

Use Supertest to send requests to the app without opening a real port, for example await request(app).get('/health').expect(200). Mock outside services or run them in containers. Keep the app setup in a separate file from listen() so tests can import it.

98. How do you mock a module in tests?

With node:test, use mock.method() on an object, or mock.module() with the module mocks flag turned on. With Jest or Vitest, use jest.mock or vi.mock. Prefer injecting dependencies where you can, so tests pass fakes in directly.

99. How do you containerize a Node app?

Use an official slim Node LTS image and copy package.json and the lock file first. Then run npm ci --omit=dev, copy the source, and run as a non-root user. Also handle SIGTERM so the container stops cleanly.

100. How do you upgrade a Node app to a new LTS?

Read the release notes for breaking changes, update the engines field and CI images, and run the full test suite. Then deploy to a small share of traffic first. Native add-ons often need a rebuild, so check those early.

Read also: 100 Database Questions for Interview

A Typical Node.js Coding Task, Worked Through

Many Node coding rounds ask you to build a small API in 45 to 60 minutes. A common prompt is a URL shortener or a to-do API with three or four routes. So practise one end to end before the interview.

For example, a URL shortener task usually needs these steps:

  1. Create an Express or Fastify app with a POST /links route that takes a long URL.
  2. Check the input with a schema, and return 400 for a bad URL.
  3. Make a short code with crypto.randomBytes(5).toString('base64url').
  4. Store the pair in a Map for the round, and mention that production would use Redis or a database.
  5. Add GET /:code that redirects with status 302, or returns 404.
  6. Write two tests with Supertest or node:test, one for each route.

Also, talk while you code. Interviewers want to hear why you picked status codes, how you would rate-limit, and what breaks at a million links. If you need more practice projects, these free coding websites have Node tracks, and this API integration checklist covers the checks real APIs need.

Node.js release table on nodejs.org showing LTS and end-of-life versions
Screenshot: nodejs.org

Other Questions About Node.js Interviews

Do I need to know a database for a Node.js role?

Yes, at least one. Most Node jobs pair it with PostgreSQL, MySQL or MongoDB, plus Redis for caching. Know how to run a query safely, use a connection pool and add an index.

Is Express still worth learning?

Yes. Many production apps run on Express, and its middleware model shows up in other frameworks too. However, also learn one newer option, such as Fastify or NestJS, since job posts often name them.

What is the difference between a Node.js developer and a full-stack developer?

A Node.js developer mainly builds servers, APIs and background jobs. A full-stack developer also builds the front end, often in React or Angular. If you are not sure which side a job sits on, this guide on websites vs web applications explains the split in product terms.

Should I mention Deno or Bun?

Mention them only if you have used them. Both are JavaScript runtimes that compete with Node. Interviewers may ask how they differ, so know that Deno has built-in permissions and that Bun focuses on speed and an all-in-one toolkit.

Joydeep Bhattacharya Avatar

Written by

Founder, Editor and Business Reporter, Bizolaunch

Free Tools for Founders

Calculators and templates built by Bizolaunch. Run the numbers in minutes.

Keep Reading