Lesson 133 of 133 ยท Practice and Review
Node.js Interview Questions and Answers
49 Node.js interview questions with short answers and code: event loop, streams, modules, async, scaling, security and performance, plus code-reading puzzles.
Node.js interviews test two things: whether you understand how the runtime really behaves (why a busy loop blocks every request, what the difference is between process.nextTick and a promise callback, what pipeline fixes that .pipe() does not) and whether you can explain it in plain words. This page collects 49 questions that come up again and again for backend and full-stack roles, grouped by level and topic, with short answers you can expand in your own words.
Try to answer each question out loud before you open it. If you cannot explain an idea in two or three sentences, follow the link to its lesson and review it. Six questions near the end ask you to read code and predict the output: make your prediction first, then press Run.
A short correct answer with a tiny example beats a long recital. Name the trap ("a synchronous loop blocks the event loop for everyone"), the safe habit ("I move CPU-heavy work to a worker thread") and the tool that shows the problem ("a CPU profile or event-loop delay metrics"). That is what makes an answer sound like experience instead of memorization.
Junior level
Basics
What is Node.js?
Node.js is a JavaScript runtime built on Google's V8 engine and the libuv library. It runs JavaScript outside the browser and gives it access to files, networks, processes and timers through built-in modules. It is used for APIs, command-line tools, build tools and real-time services. See Getting Started with Node.js and How Node.js Works.
Is Node.js a language, a framework or a runtime?
A runtime. The language is JavaScript (or TypeScript, compiled or type-stripped to JavaScript). Frameworks such as Express or Fastify are libraries built on top of the runtime. Node itself provides the engine, the event loop and the standard library.
Is Node.js single-threaded?
Your JavaScript runs on one main thread, but Node as a whole is not single-threaded. libuv keeps a thread pool (four threads by default) for file system calls, DNS lookups, crypto and compression, the operating system handles network I/O asynchronously, and you can start extra threads with worker_threads. The accurate answer is: one thread runs your JavaScript, and I/O is done outside it. See The Event Loop.
What is the difference between CommonJS and ES modules?
CommonJS (require, module.exports) loads modules synchronously at run time and is the original Node format. ES modules (import, export) are the language standard: they are analyzed statically, load asynchronously, support top-level await and give live bindings. New code should use ESM; CommonJS remains common in older packages. Modern Node can also require() an ES module that has no top-level await. See ES Modules, CommonJS Modules and ESM and CommonJS Together.
What does the node: prefix in imports mean?
import fs from 'node:fs' makes it explicit that you want the built-in module, never an npm package with the same name. It also lets Node add new built-ins without clashing with packages. Some modules, such as node:test and node:sqlite, can only be imported with the prefix.
What is package.json for?
It describes the project: name, version, dependencies, scripts, the module type ("type": "module"), entry points (main, exports) and the supported Node versions (engines). npm install reads it, and a lock file records the exact versions installed. See package.json.
What is the difference between dependencies and devDependencies?
dependencies are needed when the program runs in production. devDependencies are only needed to build, test or lint. npm install --omit=dev skips the second group on a server, which gives smaller and safer installs.
Asynchronous basics
What is a callback, and what is "callback hell"?
A callback is a function you pass to be called later, when an operation finishes. Node's classic convention is error-first: callback(error, result). Nesting many of them produces deeply indented code where errors are easy to lose. Promises and async/await flatten the structure and give one place to catch errors. See Callbacks, Promises and async/await.
How do you read a file in modern Node?
import { readFile } from 'node:fs/promises'; const text = await readFile('notes.txt', 'utf8');
The promise-based API never blocks the event loop. The Sync versions (readFileSync) do block, so they are fine in start-up code or scripts but not inside a request handler. See fs.promises.
What happens if you forget await?
You get a promise object instead of the result, and errors inside it become unhandled rejections that can crash the process. Typical symptoms are Promise { <pending> } in the output or code that runs "too early". Enable a lint rule against floating promises.
What is the difference between Promise.all, allSettled, race and any?
Promise.all resolves with every result, or rejects as soon as one fails. allSettled waits for all and reports each outcome. race settles with the first promise to settle, success or failure. any resolves with the first success and rejects only if all fail. Use all for "need everything", allSettled for "report each", and any for "fastest working mirror".
How do you handle errors in async code?
Use try/catch around await, attach .catch() to promise chains, and never leave a promise unhandled. Wrap errors with context using new Error('message', { cause: error }). For synchronous callback APIs use the error-first convention. For event emitters, always listen for 'error'. See Errors.
What is the difference between setTimeout, setImmediate and process.nextTick?
setTimeout(fn, 0) runs in the timers phase of the next loop iteration, after at least the delay. setImmediate runs in the check phase, right after the poll phase of the current iteration. process.nextTick runs before the loop continues, before promise callbacks, and starves I/O if you keep scheduling it. See Timers.
Mid level
The event loop and async internals
Describe the phases of the event loop.
Each iteration goes through: timers (expired setTimeout/setInterval callbacks), pending callbacks, internal idle/prepare, poll (new I/O events, waits here if there is nothing else), check (setImmediate) and close callbacks. Between callbacks, Node drains process.nextTick first and then the promise microtask queue. See The Event Loop.
Why is blocking the event loop bad, and how do you find it?
While a synchronous function runs, no other callback can run: no requests are answered, no timers fire. One slow JSON.parse of a huge file, a regular expression with catastrophic backtracking or a CPU loop stalls every user. Measure event-loop delay with perf_hooks.monitorEventLoopDelay, take a CPU profile, and move heavy work to a worker thread or another process. See Performance Hooks and Worker Threads.
What is the libuv thread pool and when does it matter?
It is a pool of four threads (change with UV_THREADPOOL_SIZE) used for file system operations, dns.lookup, crypto.pbkdf2/scrypt, zlib and similar. If many slow tasks fill the pool, other tasks queue behind them, which looks like random latency. Network sockets do not use it.
What is the difference between microtasks and macrotasks?
Microtasks (promise callbacks, queueMicrotask) run right after the current operation, before the loop moves on, and the queue is drained completely. Macrotasks (timers, I/O callbacks, setImmediate) run one per loop phase step. Endless microtasks starve everything else.
How do you run many async tasks, but not all at once?
Use a small pool: a fixed number of workers pull the next task from a shared index, or use a library such as p-limit. Promise.all(items.map(fn)) starts everything immediately, which can exhaust sockets or overload a database. See Concurrency Control.
How do you cancel an async operation?
Pass an AbortSignal. fetch, fs.promises, timers/promises, events.once and streams accept { signal }. AbortSignal.timeout(ms) makes a timeout, and AbortSignal.any([...]) combines signals. See Abort Signals.
Streams and buffers
What is a stream and why use it?
A stream processes data in chunks instead of loading it all into memory. A 5 GB file can be copied or compressed with a few megabytes of RAM, and the first bytes can be sent before the last ones are read. Streams are Readable, Writable, Duplex and Transform. See Streams Introduction.
What is backpressure?
It is the signal that a consumer is slower than the producer. writable.write() returns false when its buffer is full, and the producer should wait for 'drain'. If it ignores the signal, memory grows without limit. pipeline and for await handle backpressure for you. See Backpressure and pipeline.
Why prefer pipeline over .pipe()?
.pipe() does not forward errors and does not destroy the other streams when one fails, so file descriptors and memory leak. stream.pipeline (also the promise version in node:stream/promises) propagates errors, cleans up every stage and tells you when everything is finished.
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 fixed-size chunk of raw bytes, a subclass of Uint8Array, allocated outside the V8 heap. It is used for files, sockets, encodings (utf8, base64, hex) and binary protocols. Buffer.alloc(n) is zero-filled and safe; Buffer.allocUnsafe(n) is faster but may contain old memory. See Buffers.
How do you read a very large file line by line?
Use readline over a read stream with for await, which keeps memory flat:
import { createReadStream } from 'node:fs'; import { createInterface } from 'node:readline'; const lines = createInterface({ input: createReadStream('big.csv'), crlfDelay: Infinity }); for await (const line of lines) { // handle one line }
Never readFile a file whose size you do not control. See Streaming Large Data.
Events, modules and HTTP
How does EventEmitter work?
An emitter keeps a list of listeners per event name; emit calls them synchronously in registration order. on adds a listener, once adds one that runs a single time, off removes one. Emitting 'error' with no listener throws and can crash the process. Listeners are not async-aware: a rejected promise inside one is not caught by the emitter. See Events.
How does require() resolve and cache modules?
Node resolves a path or package name to a file, loads and runs it once, and stores the exports in require.cache keyed by the filename. Later require calls return the same object, so modules behave like singletons and circular dependencies see partially filled exports. ESM has a similar module map keyed by URL.
How do you create an HTTP server without a framework?
import http from 'node:http'; const server = http.createServer((request, response) => { response.writeHead(200, { 'content-type': 'text/plain' }); response.end('hello'); }); server.listen(3000);
The handler receives the request (a readable stream) and the response (a writable stream). You do routing, body parsing and error handling yourself, which is what Express and Fastify add. See HTTP Servers and Routing.
What is middleware?
A function that receives the request, the response and a next function. It can read or change them, end the response, or call next() to pass control on. Logging, authentication, parsing and error handling are typical middleware. Order matters: authentication must come before the handlers it protects. See Middleware and Express.
How do you read environment variables and configuration safely?
Read process.env once at start-up, validate it (required values present, numbers parsed) and fail fast with a clear message. Keep secrets out of the repository; load a local .env with node --env-file=.env or process.loadEnvFile(). Never log secrets. See Secrets and Configuration.
Testing
How do you test Node code without extra libraries?
Use the built-in node:test runner with node:assert: test(), describe(), hooks, mocks, snapshot support and coverage via --experimental-test-coverage. Run with node --test. See The Node Test Runner and Assertions.
How do you test code that uses timers or the network?
Mock the clock (mock.timers.enable()) so tests do not wait, and test servers by listening on port 0 and calling them with fetch. Inject dependencies (a sleep function, a client) so tests can replace them. See Mocking and Timers and Testing HTTP.
Express, Passport and testing tools
What does body-parsing middleware do, and why does order matter?
A request body arrives as a stream of bytes. express.json() (built on the old body-parser package) reads that stream, parses it as JSON and puts the result in req.body; express.urlencoded() does the same for HTML forms. A route registered before the parser sees req.body as undefined. Always set a size limit (express.json({ limit: '100kb' })) so one client cannot send a gigabyte. Multipart forms (file uploads) need a different parser such as Multer. See Express request bodies and Built-in middleware.
What is CORS, and who enforces it?
Browsers enforce the same-origin policy: a page from one origin cannot read responses from another unless the server opts in with Access-Control-Allow-Origin and related headers. The cors middleware sets those headers. CORS protects the user's browser, not your server: curl ignores it, so it never replaces authentication. Allow specific origins instead of * when credentials (cookies) are involved, and remember that "preflight" OPTIONS requests must be answered too. See Headers, Cookies and Caching.
What is Passport and how does a strategy work?
Passport is authentication middleware for Express. It does not store users; it runs a strategy, a small module that knows one way of proving identity (username and password, a JWT, "log in with Google"). You give the strategy a verify callback that looks the user up and calls done(err, user). With sessions, serializeUser stores a small identifier in the session and deserializeUser loads the full user from it on each request, which then appears as req.user. With token strategies there is no session; every request carries its own credential. See Sessions and cookies and JWT authentication.
How do sessions work, and what makes a session cookie safe?
The server keeps the data and gives the browser a random session id in a cookie. The cookie should be HttpOnly (scripts cannot read it), Secure (HTTPS only), SameSite=Lax or Strict (limits cross-site sends) and carry a sensible expiry. The default in-memory store leaks memory and does not survive restarts or scale across servers; use Redis or a database store in production, and regenerate the session id after login to prevent session fixation. See Sessions, JWT and Authentication.
How do you handle errors in Express, including async ones?
Error-handling middleware has four parameters (err, req, res, next) and is registered after the routes. Throwing inside a synchronous handler reaches it automatically. In Express 5, a rejected promise from an async handler also reaches it; in Express 4 you must catch and call next(err) yourself or wrap handlers. Send a safe message to the client and log the details. See Error handling in Express.
What does the test pyramid mean for a Node service?
Many fast unit tests for pure logic, fewer integration tests that run real components together (the HTTP layer with a test database), and a handful of end-to-end tests that exercise the whole deployed system. The lower you test, the faster and more precise the failure; the higher you test, the more realistic. Over-investing in slow end-to-end tests gives a suite people stop running. See Testing HTTP and The Node Test Runner.
What do Jest, Mocha, Chai, Supertest and Sinon each do?
Jest is an all-in-one runner with assertions, mocks, snapshots and coverage. Mocha is only a runner (describe, it, hooks) and is paired with an assertion library such as Chai (expect(x).to.equal(y)). Supertest calls an Express app in-process with request(app).get('/path') and asserts on status and body. Sinon provides spies, stubs, mocks and fake timers. Node's own node:test plus node:assert now covers most of this without dependencies. See Mocking and Timers and the Jest tutorial.
How do you handle file uploads?
Parse multipart/form-data with a library (Multer, Busboy, Formidable) that streams the file instead of loading it all into memory. Limit file size and count, check the real content type rather than trusting the filename, generate your own stored file name (never use the client's), and store files outside the web root or in object storage. See File Uploads and Multipart and Express file uploads.
Senior level
Scaling and architecture
How do you use all CPU cores?
Run several processes: the cluster module or, more commonly today, a process manager or container orchestrator starting one process per core behind a load balancer. Inside one process use worker_threads for CPU-heavy tasks. Keep application state out of process memory (use Redis or a database) so any process can serve any request. See Cluster and Scaling and Scalability Patterns.
worker_threads, child_process or cluster: when do you use each?
worker_threads: CPU work inside one app, with shared memory (SharedArrayBuffer) and cheap messaging. child_process: run another program or isolate untrusted or crashy work in its own process. cluster: several copies of the same server sharing a port. See Worker Threads, Child Processes.
How do you shut a server down gracefully?
On SIGTERM: stop accepting new connections (server.close()), let in-flight requests finish, close database pools and queues, then exit. Set a deadline (a few seconds) after which you call server.closeAllConnections() and exit anyway. Report unhealthy in the readiness check as soon as shutdown begins so the load balancer stops sending traffic. See Graceful Shutdown.
How do you keep a Node service healthy under load?
Set timeouts on every outgoing call, limit concurrency and body sizes, add retries with backoff and jitter only for safe errors, cache expensive results, apply rate limits, and expose health and metric endpoints. Watch event-loop delay, heap size, open handles and error rate. See Caching, Performance Tuning and Logging.
What is AsyncLocalStorage used for?
It carries a value through a chain of async calls without passing it as a parameter, like a per-request context holding a request id for logs. Node tracks the async execution context for you. See AsyncLocalStorage.
Performance and memory
How do you find and fix a memory leak?
Watch heap growth over time (process.memoryUsage(), metrics), take heap snapshots at two moments and compare retained objects, and look for the usual suspects: unbounded caches or maps, listeners added on every request, closures holding large objects, timers never cleared. Fix by bounding caches, removing listeners and clearing timers. See V8 and Memory and Diagnostics.
How does garbage collection affect a Node service?
V8 uses a generational collector: a young generation collected often and cheaply, and an old generation collected incrementally and concurrently. Large old heaps cause longer pauses. Reduce allocation in hot paths, avoid keeping big objects alive, and size the heap with --max-old-space-size to match the container limit.
How would you profile a slow endpoint?
Reproduce under load, record a CPU profile (--cpu-prof or the inspector), read the flame graph for the widest frames, and check whether the time is JavaScript, garbage collection or waiting on I/O. Use performance.mark/measure and monitorEventLoopDelay to separate them. Fix the biggest cost first and measure again. See Performance Hooks.
Why is JSON.parse of a large payload a risk?
It is synchronous, so a multi-megabyte body blocks the loop for every other request, and attackers can send big or deeply nested documents. Limit body sizes, validate shape after parsing, and stream-parse large data formats such as NDJSON line by line. See JSON Data.
Security
How do you store passwords?
Never store plain text or a fast hash. Use a slow, salted password hash such as scrypt (built in) or Argon2, with a unique random salt per password, and compare in constant time with crypto.timingSafeEqual. See Password Hashing.
What are the most common web security problems in Node apps?
Injection (SQL, command, NoSQL), cross-site scripting, cross-site request forgery, broken authentication and sessions, missing authorization checks, secrets in the repository, unvalidated input, path traversal when serving files, and vulnerable dependencies. Defenses: parameterized queries, output encoding, validated input, security headers, least privilege and npm audit in CI. See Web Security and Validation.
What is path traversal and how do you prevent it?
A user-supplied name like ../../etc/passwd escapes the folder you meant to serve. Resolve the final path with path.resolve(root, name) and check that it still starts with the root (plus a separator) before opening it, or only accept known ids. See Paths and Permissions.
Why is child_process.exec dangerous with user input?
exec runs the string through a shell, so input like ; rm -rf / becomes a command. Use execFile or spawn with an argument array, which does not use a shell, and validate what you pass. See Child Processes.
How do you randomize safely?
Math.random() is not cryptographically secure. Use crypto.randomBytes, crypto.randomUUID() or crypto.randomInt for tokens, ids and secrets. See Random Values and IDs.
How do you keep dependencies safe?
Commit the lock file, install with npm ci in CI, run npm audit, update regularly, prefer few well-maintained dependencies, review install scripts, and pin the Node version. Every dependency is code you run with your app's full privileges.
TypeScript, tooling and ecosystem
Can Node run TypeScript directly?
Recent Node versions can run .ts files by stripping erasable type syntax (annotations, interfaces, type aliases) without type-checking. Features that need code generation, such as enums, need extra flags. Run tsc --noEmit separately for real type checking. See Node and TypeScript.
What does the exports field in package.json do?
It defines the public entry points of a package and blocks deep imports of everything else. It supports conditions such as import and require, so one package can serve both module formats. See Creating Packages.
Express, Fastify or no framework?
Express is the most familiar and has the largest ecosystem. Fastify is faster and has schema-based validation built in. Plain node:http is fine for tiny services or when you want zero dependencies. Choose on team knowledge and ecosystem, not on micro-benchmarks. See Express.
Code-reading questions
What does this print? (event loop order)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
The synchronous line goes first. After it, nextTick runs before promise callbacks, and then the microtasks run in the order they were queued. The relative order of timeout and immediate from the main module depends on process performance and is not guaranteed; inside an I/O callback immediate always comes first.
What does this print? (await in a loop)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Both give a, b, c, because Promise.all keeps the input order. The difference is time: the loop takes about the sum of the delays, Promise.all about the longest one.
What does this print? (unhandled rejection)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
started is printed first, then the process ends with exit code 1 and the message Error: database is down with a stack trace pointing at main.mjs. Since Node 15 an unhandled rejection is a crash by default. The fix is to await load() inside try/catch or to attach .catch().
What does this print? (Buffer memory sharing)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
subarray (and the old slice) returns a view of the same memory, so changing it changes the original: Jello. Buffer.from(buffer) copies the bytes. Forgetting this causes bugs where a "small" buffer keeps a big one alive or is modified by someone else.
What does this print? (module cache)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
The file runs once and both variables hold the same exports object, so the counter is shared: 1 2 3. That is why modules work as singletons, and why a module holding per-request state is a bug.
What does this print? (pipeline error handling)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
pipeline rejects with the first error, and it destroys every stage, so the sink is closed and the numbers after the failure never arrive. With plain .pipe() the sink would stay open and the error would have no handler.
Summary
- At junior level, explain what Node is, the module systems, callbacks versus promises,
async/awaitand error handling, and the difference betweennextTick,setImmediateand timers. - At mid level, know the event loop phases, microtasks, the thread pool, streams with backpressure,
pipeline, buffers, events, middleware and the built-in test runner. - At senior level, connect the runtime to production: using every core, graceful shutdown, memory leaks and profiling, timeouts and limits, and security basics such as password hashing, injection and path traversal.
- Practice with the core problems and the streams, HTTP and concurrency problems, reread the cheat sheet, and build one of the projects so you have real stories to tell.
That is the end of the Node.js course. You now know the runtime, its standard library and the habits of production Node developers. The best next step is to build something of your own, read other people's code, and keep this page for your next interview. Good luck!
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Node.js lessons completed