Node.js · Production

Interview Questions

29 questions you are likely to be asked about Node.js, from beginner to experienced level — each with a spoken-style answer, a common follow-up and a link to the lesson behind it.

Advanced 15 min Topic 37 of 37
0/37 in Node.js

Beginner questions (9)

01What is middleware in Express?

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).

Learn: Middleware
02What is Node.js?

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.

Learn: Introduction to Node.js
03What is the purpose of package.json and package-lock.json?

package.json describes the project, its scripts and dependency ranges. package-lock.json records the exact installed versions so every install is reproducible.

Learn: package.json
04CommonJS vs ES modules in Node.js?

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.

Learn: CommonJS and ES Modules
05What is npm, and what is the difference between dependencies and devDependencies?

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.

Learn: Installation and npm
06What does semantic versioning mean in package.json?

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.

Learn: package.json
07How do you read a file in Node.js?

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.

JavaScript Illustrative
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./notes.txt', import.meta.url), 'utf8');
console.log(text.length);
Learn: File System
08What is the path module used for?

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.

Learn: Path Module
09What is a callback and what is callback hell?

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.

Learn: Callbacks

Intermediate questions (14)

01How can Node.js handle many connections on a single thread?

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.

Learn: Node.js Architecture
02Where should a browser app store a JWT?

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.

Learn: JWT
03What are streams and why use them?

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.

Learn: Streams
04What is the EventEmitter?

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.

Learn: EventEmitter
05How do you handle errors in Express?

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.

Learn: Error Handling
06How do you manage configuration and secrets?

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.

Learn: Environment Variables
07What is a Buffer?

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").

Learn: Buffers
08What phases does the Node.js event loop have?

Timers (setTimeout/setInterval), pending callbacks, poll (I/O), check (setImmediate) and close callbacks. Between each callback Node drains process.nextTick and promise microtasks.

Learn: Node.js Architecture
09How do you build a server with only the http module?

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.

Learn: HTTP Module
10How do you organise routes in Express?

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.

Learn: Routing
11req.params vs req.query vs req.body?

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.

Learn: Request and Response
12How do you connect to MySQL safely from Node?

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.

Learn: MySQL Integration
13How should passwords be stored?

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.

Learn: Password Hashing
14How do you handle file uploads in Express?

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).

Learn: File Uploads

Experienced questions (6)

01How do you use multiple CPU cores in Node.js?

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.

Learn: Node.js Architecture
02How do you secure a Node.js API?

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.

Learn: API Security
03How do you log in a production Node.js service?

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.

Learn: Logging
04How do you test an Express API?

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.

Learn: Testing
05How do you deploy a Node.js app?

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.

Learn: Deployment
06How do you run CPU-heavy work without blocking requests?

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.

Learn: Asynchronous Programming
Progress is saved in this browser. Sign in to sync.