Top 25 Node.js Interview Questions
Curated questions covering event loop, streams, modules, Express, async patterns, clustering, and npm.
What is Node.js and what makes it unique?
Node.js is a JavaScript runtime built on Chrome's V8 engine. It is single-threaded, non-blocking, and event-driven, making it ideal for I/O-intensive applications. It uses an event loop to handle concurrent operations without multiple threads.
What is the event loop in Node.js?
The event loop allows Node.js to perform non-blocking I/O by offloading operations to the OS. It processes callbacks in phases: timers (setTimeout/setInterval), pending callbacks, idle/prepare, poll (I/O), check (setImmediate), and close callbacks.
What is the difference between synchronous and asynchronous code in Node.js?
- Synchronous — blocks execution until the operation completes. Avoid for I/O in Node.js.
- Asynchronous — uses callbacks, Promises, or async/await to handle operations without blocking the event loop.
- Node.js is designed for async I/O; synchronous operations block the single thread.
What are streams in Node.js?
Streams are objects that let you read or write data in chunks rather than loading everything into memory. Types: Readable, Writable, Duplex (both), Transform (modify data). Used for file I/O, HTTP requests, and data processing.
const fs = require("fs");
const readable = fs.createReadStream("large.txt");
const writable = fs.createWriteStream("output.txt");
readable.pipe(writable); // stream data without loading all into memory
What is the difference between require() and import?
- require() — CommonJS (CJS) module system; synchronous; dynamic loading supported; default in Node.js.
- import — ES Modules (ESM); static; tree-shakeable; requires .mjs extension or "type":"module" in package.json.
- Node.js supports both, but they cannot be freely mixed.
What is the difference between process.nextTick() and setImmediate()?
- process.nextTick() — executes callback before the next event loop iteration (before I/O callbacks). Highest priority.
- setImmediate() — executes callback in the check phase of the event loop, after I/O callbacks.
- Use nextTick for immediate async operations; setImmediate for deferring to the next iteration.
What is Express.js?
Express is a minimal, unopinionated web framework for Node.js. It provides routing, middleware support, request/response handling, and template engine integration. It is the most popular Node.js web framework.
const express = require("express");
const app = express();
app.use(express.json());
app.get("/users", (req, res) => res.json({ users: [] }));
app.listen(3000);
What is middleware in Express?
Middleware functions have access to req, res, and next. They execute in order and can modify the request/response, end the cycle, or call next() to pass control. Used for logging, authentication, parsing, error handling, and CORS.
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // pass to next middleware
});
What is the difference between callbacks, Promises, and async/await in Node.js?
- Callbacks — original async pattern; leads to callback hell with nested operations.
- Promises — chainable with .then()/.catch(); avoids nesting; better error handling.
- async/await — syntactic sugar over Promises; synchronous-looking code; try/catch for errors. Preferred modern approach.
What is the Node.js cluster module?
The cluster module allows creating child processes (workers) that share the same server port. Since Node.js is single-threaded, clustering utilises multiple CPU cores. The master process manages workers and distributes incoming connections.
const cluster = require("cluster");
const os = require("os");
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require("./server"); // each worker runs the server
}
What is the difference between spawn, exec, and fork in child_process?
- spawn — launches a new process; streams stdout/stderr; best for large output.
- exec — runs a command in a shell; buffers output; best for small output.
- fork — special spawn for Node.js scripts; creates IPC channel for message passing between parent and child.
What is npm and what is package.json?
npm (Node Package Manager) manages JavaScript packages. package.json defines project metadata, dependencies, devDependencies, scripts, and version. package-lock.json locks exact dependency versions for reproducible installs.
What is the difference between dependencies and devDependencies?
- dependencies — packages required at runtime (express, mongoose, axios).
- devDependencies — packages only needed during development (jest, eslint, nodemon, webpack).
- Install with --save-dev for devDependencies; they are excluded from production installs with npm install --production.
What is the Buffer class in Node.js?
Buffer is a global class for handling binary data directly in memory. Used for reading files, network packets, and streams. Buffers are fixed-size allocations outside the V8 heap.
const buf = Buffer.from("Hello", "utf8");
console.log(buf.toString("hex")); // 48656c6c6f
console.log(buf.length); // 5
What is the EventEmitter in Node.js?
EventEmitter is the core of Node.js's event-driven architecture. Objects can emit named events and register listeners. Many built-in modules (streams, HTTP) extend EventEmitter.
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
emitter.on("data", (msg) => console.log(msg));
emitter.emit("data", "Hello!"); // "Hello!"
What is the difference between __dirname and __filename?
__dirname is the absolute path of the directory containing the current module. __filename is the absolute path of the current module file. Both are available in CommonJS modules but not in ES Modules (use import.meta.url instead).
What is REPL in Node.js?
REPL (Read-Eval-Print Loop) is an interactive shell for executing Node.js code. Run with the node command. Useful for testing snippets, debugging, and exploring APIs.
What is the path module?
The path module provides utilities for working with file and directory paths in a cross-platform way. Key methods: path.join(), path.resolve(), path.basename(), path.dirname(), path.extname().
const path = require("path");
path.join("/users", "alice", "docs"); // /users/alice/docs
path.resolve("./config.json"); // absolute path
path.extname("file.js"); // ".js"
What is the fs module?
The fs (file system) module provides APIs for interacting with the file system. Supports both synchronous (readFileSync) and asynchronous (readFile with callback or promises) operations. Use fs.promises for async/await.
const fs = require("fs/promises");
const data = await fs.readFile("file.txt", "utf8");
await fs.writeFile("out.txt", data);
What is the difference between PUT and PATCH in REST APIs?
- PUT — replaces the entire resource with the provided data. Idempotent.
- PATCH — partially updates a resource with only the provided fields. More efficient for partial updates.
What is CORS and how do you handle it in Node.js?
CORS (Cross-Origin Resource Sharing) controls which origins can access your API. In Express, use the cors middleware to set appropriate headers.
const cors = require("cors");
app.use(cors({ origin: "https://example.com", methods: ["GET","POST"] }));
What is JWT and how is it used in Node.js?
JWT (JSON Web Token) is a compact, self-contained token for authentication. It has three parts: header, payload, and signature. Used for stateless authentication — the server verifies the token without storing session data.
const jwt = require("jsonwebtoken");
const token = jwt.sign({ userId: 1 }, process.env.SECRET, { expiresIn: "1h" });
const decoded = jwt.verify(token, process.env.SECRET);
What is the difference between SQL and NoSQL databases?
- SQL (MySQL, PostgreSQL) — structured, table-based, ACID transactions, fixed schema, good for relational data.
- NoSQL (MongoDB, Redis) — flexible schema, horizontal scaling, various data models (document, key-value, graph).
- Choose based on data structure, consistency requirements, and scale needs.
What is rate limiting and why is it important?
Rate limiting restricts the number of requests a client can make in a time window. It prevents abuse, DDoS attacks, and API overuse. In Express, use express-rate-limit middleware.
const rateLimit = require("express-rate-limit");
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); // 100 req per 15 min
What is the difference between monolithic and microservices architecture?
- Monolithic — single deployable unit; simpler to develop initially; harder to scale and maintain as it grows.
- Microservices — independent services communicating via APIs; independently deployable and scalable; more complex infrastructure.