Node.js Interview Questions
Answers written to be said out loud in an interview — each with a common follow-up question and a link to the tutorial that explains it in depth.
- Beginner
- 9
- Intermediate
- 14
- Experienced
- 6
01What is middleware in Express?Beginner
A function (req, res, next) that runs during the request lifecycle. It can modify req/res, end the response, or call next() to pass control on. Error-handling middleware has four parameters (err, req, res, next).
02What is Node.js?Beginner
A JavaScript runtime built on Chrome’s V8 engine that runs JavaScript outside the browser. It uses an event-driven, non-blocking I/O model, which suits APIs and real-time apps.
03What is the purpose of package.json and package-lock.json?Beginner
package.json describes the project, its scripts and dependency ranges. package-lock.json records the exact installed versions so every install is reproducible.
04CommonJS vs ES modules in Node.js?Beginner
CommonJS uses require() and module.exports and loads synchronously. ES modules use import/export, load asynchronously and are the standard. Enable ESM with "type": "module" or the .mjs extension.
05What is npm, and what is the difference between dependencies and devDependencies?Beginner
npm installs packages and runs scripts. dependencies are needed at runtime (express, mysql2). devDependencies are only for development and builds (typescript, vitest, eslint) and are skipped with npm ci --omit=dev.
06What does semantic versioning mean in package.json?Beginner
Versions are MAJOR.MINOR.PATCH. ^1.4.2 allows any 1.x.x at or above 1.4.2, ~1.4.2 allows 1.4.x only, and an exact version pins it. The lock file records the exact versions installed.
07How do you read a file in Node.js?Beginner
Use the promise API: await readFile(path, "utf8") from node:fs/promises. Avoid readFileSync in servers because it blocks the event loop; for large files use a stream.
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./notes.txt', import.meta.url), 'utf8');
console.log(text.length);
08What is the path module used for?Beginner
Building and parsing file paths in an operating-system-safe way: path.join, path.resolve, path.basename, path.extname and path.dirname, instead of concatenating strings with slashes.
09What is a callback and what is callback hell?Beginner
A function passed to another function to run later, often with an (err, result) signature in Node. Nesting many of them creates deeply indented, hard-to-handle code — callback hell. Promises and async/await flatten it.
10How can Node.js handle many connections on a single thread?Intermediate
Node uses non-blocking I/O. Slow operations (network, disk) are delegated to the operating system or libuv’s thread pool, and their callbacks are queued on the event loop when complete, so the main thread is never idle-waiting.
11Where should a browser app store a JWT?Intermediate
Preferably in an httpOnly, Secure, SameSite cookie, which JavaScript cannot read, limiting the impact of XSS. Pair it with CSRF protection for state-changing requests.
12What are streams and why use them?Intermediate
Streams process data piece by piece instead of loading it all into memory. Types: Readable, Writable, Duplex and Transform. They are ideal for large files, uploads and proxying, and pipeline() handles errors and backpressure.
13What is the EventEmitter?Intermediate
A core class that lets objects emit named events and register listeners with on/once. Many Node APIs (streams, HTTP servers) are built on it.
14How do you handle errors in Express?Intermediate
Throw or pass errors to next(err) and register a final error-handling middleware with four parameters (err, req, res, next). Express 5 forwards rejected promises from async handlers automatically. Never leak stack traces to clients.
15How do you manage configuration and secrets?Intermediate
Read them from environment variables (process.env), use a .env file only in development, validate them at startup, and never commit secrets or expose them to the client bundle.
16What is a Buffer?Intermediate
A fixed-length chunk of raw binary data outside the V8 heap, used for files, sockets and crypto. Convert with Buffer.from(text, "utf8") and buf.toString("base64").
17What phases does the Node.js event loop have?Intermediate
Timers (setTimeout/setInterval), pending callbacks, poll (I/O), check (setImmediate) and close callbacks. Between each callback Node drains process.nextTick and promise microtasks.
18How do you build a server with only the http module?Intermediate
http.createServer((req, res) => …) receives every request; you check req.method and req.url yourself, read the body from the stream, set headers and call res.end(). Express adds routing, middleware and helpers on top.
19How do you organise routes in Express?Intermediate
Group related routes in express.Router() modules (routes/products.js), mount them with app.use("/api/products", router), and keep handlers thin by moving logic into services.
20req.params vs req.query vs req.body?Intermediate
params are route segments (/users/:id), query is the query string (?page=2), and body is the request payload, which needs express.json() or another parser. All of them are strings or untrusted input until validated.
21How do you connect to MySQL safely from Node?Intermediate
Use mysql2/promise with a connection pool created once at startup, use placeholders (?) for every value, and release connections automatically with pool.query or in finally blocks for transactions.
22How should passwords be stored?Intermediate
Hash them with a slow, salted algorithm — bcrypt (cost 12+) or argon2 — and store only the hash. Compare with bcrypt.compare. Never encrypt, never use plain SHA-256 and never log passwords.
23How do you handle file uploads in Express?Intermediate
Use multer with limits on size and file count, a fileFilter that checks MIME type and extension, random server-generated file names and storage outside the public folder (or in S3).
24How do you use multiple CPU cores in Node.js?Experienced
Run several processes with the cluster module or a process manager like PM2, or scale horizontally with containers behind a load balancer. For CPU-heavy work inside one process, use worker_threads.
25How do you secure a Node.js API?Experienced
Validate all input, use parameterised queries, hash passwords with bcrypt/argon2, set security headers with helmet, configure CORS narrowly, rate-limit, keep dependencies patched (npm audit) and log without sensitive data.
26How do you log in a production Node.js service?Experienced
Use a structured logger such as pino: JSON logs with levels, a request id per request, no secrets or bodies, and logs written to stdout for the platform to collect. Add pino-http for access logs.
27How do you test an Express API?Experienced
Unit-test services with Vitest or node:test, and test routes with supertest against the app (without listen). Use a separate test database or mock the repository, and run tests in CI.
28How do you deploy a Node.js app?Experienced
Build once, run with NODE_ENV=production behind a reverse proxy (Nginx) or on a platform, use a process manager (PM2, systemd, Docker restart policy), read config from environment variables, add a health endpoint and handle SIGTERM for graceful shutdown.
29How do you run CPU-heavy work without blocking requests?Experienced
Move it off the main thread with worker_threads (or a job queue such as BullMQ processed by separate workers). Keep request handlers to I/O and quick logic.