Interview Q&A / Node.js
Node.js interview questions
The event loop on the server, streams, modules and building APIs with Express.
Prefer rapid revision? Practise Node.js short interview answers →
- What is npx and when would you use it instead of npm install?
npx runs a package's command, using a local copy if present or downloading it temporarily. It is good for one-off tools and project generators, so you avoid installing them globally.
BeginnerQuick answer1 min read - What is semantic versioning and why does it matter for npm packages?
Semantic versioning uses MAJOR.MINOR.PATCH. Increase PATCH for bug fixes, MINOR for backward-compatible features, MAJOR for breaking changes, so users can judge upgrade risk from the number alone.
BeginnerQuick answer1 min read - What is the difference between fs.readFileSync, fs.readFile and fs.promises.readFile?
readFileSync blocks the thread until done. readFile takes a callback and does not block. fs.promises.readFile returns a promise for use with await. In servers, prefer the non-blocking forms.
BeginnerQuick answer1 min read - What is the difference between module.exports and exports in CommonJS?
exports is just a shortcut variable pointing at module.exports. You can add properties to either, but only module.exports is what require returns, so reassigning exports alone exports nothing.
BeginnerQuick answer1 min read - What is the difference between npm install and npm ci?
npm install can update the lock file and resolves versions from package.json. npm ci deletes node_modules and installs exactly what package-lock.json says, failing if the two disagree, which makes builds repeatable.
BeginnerQuick answer1 min read - What is the difference between path.join and path.resolve?
join just glues segments together with the correct separator. resolve builds an absolute path, processing segments right to left until it has one, and falls back to the current working directory.
BeginnerQuick answer1 min read - What is the difference between Promise.all and Promise.allSettled?
Promise.all rejects as soon as any promise rejects and gives you results only if all succeed. Promise.allSettled always waits for every promise and reports each outcome as fulfilled or rejected.
BeginnerQuick answer1 min read - What is the difference between PUT and PATCH in a REST API?
PUT replaces the whole resource with the body you send, so missing fields are cleared. PATCH changes only the fields you send. PUT is idempotent by definition; PATCH is not guaranteed to be.
BeginnerQuick answer1 min read - What is the difference between route parameters and query strings in Express?
Route parameters are part of the path, like /users/42, and identify a specific resource, read from req.params. Query strings follow a question mark, like ?page=2, and filter or tweak a request, read from req.query.
BeginnerQuick answer1 min read - Which HTTP status codes should a REST API return for create, validation errors, missing login and forbidden access?
201 Created for a successful create, 400 for bad input (or 422 for failed validation), 401 when the user is not authenticated, 403 when authenticated but not allowed, 404 for a missing resource, and 500 for server faults.
BeginnerQuick answer1 min read - Why does req.body come out undefined in Express, and what does express.json do?
Express does not read request bodies by itself. express.json() is middleware that parses JSON bodies with a JSON content type and places the result on req.body. Without it, req.body is undefined.
BeginnerQuick answer1 min read - Why does the order of middleware and routes matter in Express?
Express runs middleware and routes in the order they are registered, and a response ends the chain. A parser placed after a route never runs for it, and a catch-all placed early swallows later routes.
BeginnerQuick answer1 min read - Why should you hash passwords with bcrypt instead of SHA-256 or storing them in plain text?
Plain text leaks everything in a breach. SHA-256 is designed to be fast, so attackers can test billions of guesses per second. bcrypt is deliberately slow, adds a unique salt, and its cost can be raised over time.
BeginnerQuick answer1 min read - Why use path.join instead of joining file paths with plus signs?
path.join uses the correct separator for the operating system, normalises extra slashes and dot segments, and avoids missing or doubled slashes, so paths work on Windows, Linux and macOS.
BeginnerQuick answer1 min read - Write an Express middleware that checks a JWT and protects a route.
Read the Bearer token from the Authorization header, verify it with jwt.verify, attach the claims to req.user and call next. On a missing or invalid token, respond 401 without calling next.
BeginnerQuick answerCoding1 min read - How can CommonJS code load an ES module?
Use dynamic import(), which works in CommonJS and returns a promise. Plain require of an ES module was not allowed historically; newer Node versions added limited support, so dynamic import is the safe choice.
IntermediateQuick answer1 min read - How do you read a very large file line by line in Node.js?
Create a read stream and pass it to readline.createInterface, then loop with for await. Only a small chunk sits in memory at a time, unlike readFile, which loads the whole file.
IntermediateQuick answer1 min read - How do you send a large file to the browser without loading it all in memory?
Create a read stream of the file and pipe it into the HTTP response. Set the Content-Type and, if known, Content-Length headers first, and handle stream errors before any bytes are sent.
IntermediateQuick answer1 min read - How do you version a REST API, and why would you?
Versioning lets you change the API without breaking existing clients. The common way is a URL prefix such as /api/v1. Other options are a custom header or media type. Avoid breaking changes inside a version.
IntermediateQuick answer1 min read - How do you write a JSON file in Node.js without risking a half-written file?
Write the data to a temporary file in the same folder, then rename it over the target. Rename is atomic on the same filesystem, so readers see either the old file or the complete new one.
IntermediateQuick answer1 min read - How does bcrypt store the salt and what does the cost factor mean?
The 60-character bcrypt hash contains the algorithm version, the cost, the 22-character salt and the hash itself, so you store one string. The cost is a power of two: each +1 doubles the work.
IntermediateQuick answer1 min read - How does Express know a middleware is an error handler?
By its arity: an error-handling middleware takes four arguments (err, req, res, next). It must be registered after the routes, and errors reach it through next(err) or a thrown error in synchronous code.
IntermediateQuick answer1 min read - How should a REST API return error responses consistently?
Use one JSON shape for every error with the right HTTP status, a stable machine-readable code, a human message, and optional field details. Never leak stack traces or database errors to clients.
IntermediateQuick answer1 min read - How would you design pagination for an API endpoint that returns thousands of records?
Return a slice per request using limit and page (offset) or, for large changing data, a cursor of the last item seen. Cap the maximum limit and return total or next-page information in the response.
IntermediateQuick answer1 min read - Predict the output: setTimeout, a promise, process.nextTick and plain logs together
Synchronous code runs first, then process.nextTick callbacks, then promise callbacks (microtasks), then timers. So the order is sync, nextTick, promise, setTimeout.
IntermediateQuick answer1 min read - Should you use await inside a for loop or Promise.all for independent tasks?
For independent tasks use Promise.all with map so they run concurrently. await inside a loop runs them one by one, which is right only when each step depends on the last or order and rate limits matter.
IntermediateQuick answer1 min read - What are peerDependencies in package.json?
peerDependencies declare packages your library needs but expects the host application to install, so only one shared copy exists. Plugins and UI libraries use them, for example a React component library requiring react.
IntermediateQuick answer1 min read - What are the main phases of the Node.js event loop?
Timers, pending callbacks, idle/prepare, poll, check, and close callbacks. Timers run setTimeout callbacks, poll collects I/O, check runs setImmediate, and microtasks are drained between steps.
IntermediateQuick answer1 min read - What does idempotent mean for HTTP methods, and which methods are idempotent?
An idempotent request has the same effect on the server whether it is sent once or many times. GET, PUT, DELETE, HEAD and OPTIONS are idempotent; POST is not, and PATCH may not be.
IntermediateQuick answer1 min read - What is a circular dependency in Node.js and what happens when it occurs?
A circular dependency is when module A requires B and B requires A. In CommonJS, the second module receives A's partially filled exports at that moment, so values defined later are undefined. Fix it by restructuring.
IntermediateQuick answer1 min read