HomeInterview QuestionsNode.js Interview Questions
🟢
Free Study Guide · 2025

Top 50 Node.js Interview Questions & Answers (2025)

Node.js powers the backend of most modern Indian startups — Razorpay, CRED, Meesho, and dozens of others. These questions cover the event loop, async patterns, Express, streams, and system design concepts you'll face in backend JavaScript roles.

20 questions
Detailed answers
100% free
1What is Node.js and what makes it non-blocking?
Node.js is a JavaScript runtime built on Chrome's V8 engine that executes JavaScript outside the browser. It's non-blocking because it uses an event-driven, single-threaded architecture with an event loop that delegates I/O operations to the operating system's asynchronous APIs (via libuv). While I/O waits, the event loop handles other requests, making Node excellent for I/O-bound concurrent workloads.
2How does the Node.js event loop work?
The event loop processes tasks in phases: timers (setTimeout/setInterval callbacks), pending callbacks (I/O errors), idle/prepare, poll (wait for new I/O, execute callbacks), check (setImmediate callbacks), close callbacks. Microtasks (process.nextTick and Promises) run between phases. process.nextTick runs before any I/O — even before Promises.
3What is the difference between process.nextTick() and setImmediate()?
process.nextTick() queues a callback to run after the current operation completes but before the event loop continues to the next phase — it has the highest priority among async callbacks. setImmediate() runs in the check phase, after the poll (I/O) phase. In practice: nextTick runs before Promises; setImmediate runs after I/O callbacks in the current loop iteration.
4What is the CommonJS module system in Node.js?
CommonJS is Node.js's original module system using require() to import and module.exports or exports to export. Modules are cached after first load. Node.js also supports ES Modules (import/export) in .mjs files or when type: 'module' is set in package.json. The two systems are not interoperable without adapters — mixing them in the same project requires care.
5What are streams in Node.js?
Streams are abstract interfaces for working with streaming data, enabling processing of large files or network data without loading everything into memory. Four types: Readable (fs.createReadStream), Writable (fs.createWriteStream), Duplex (readable + writable, like a TCP socket), and Transform (modify data in transit, like zlib.createGzip). Streams use events: data, end, error, finish.
6What is the difference between spawn(), exec(), and fork() in child_process?
spawn() launches a new process and streams stdin/stdout — ideal for long-running commands producing large output. exec() runs a command in a shell and buffers the entire output — suitable for small, quick commands. fork() is a special spawn for Node.js modules — it creates a new Node.js process with a built-in IPC (message-passing) channel between parent and child.
7What is clustering in Node.js and why do you use it?
Node.js is single-threaded, so it can't natively use multiple CPU cores. The cluster module lets you spawn multiple child processes (workers) that all share the same server port. The master process distributes incoming connections to workers. A common pattern: spawn os.cpus().length workers. PM2 manages clustering in production with zero-downtime restarts.
8What is the EventEmitter in Node.js?
EventEmitter is a core Node.js class for implementing the observer pattern. Objects extend EventEmitter to emit named events (emitter.emit('event', data)) and register listeners (emitter.on('event', callback)). Most Node.js core APIs (streams, http, etc.) extend EventEmitter. Common pitfalls: forgetting to remove listeners (memory leaks) and unhandled 'error' events crashing the process.
9What is middleware in Express.js?
Middleware are functions in Express's request-response cycle with access to (req, res, next). They can execute code, modify req/res, end the request, or call next() to pass control to the next middleware. Used for: logging, auth checks, request parsing (express.json()), CORS headers, error handling. Error-handling middleware has four parameters: (err, req, res, next).
10How do you handle errors in Node.js?
Synchronous: try-catch. Async (callbacks): check the first argument (err-first convention). Promises: .catch() or try-catch in async/await. Add a global process.on('unhandledRejection') and process.on('uncaughtException') as last-resort handlers. In Express, use a 4-parameter error-handling middleware. Always log errors with context and avoid silently swallowing them.
11What is the difference between SQL and NoSQL databases?
SQL databases (PostgreSQL, MySQL) store data in structured tables with predefined schemas, enforce ACID transactions, and use JOIN queries for relational data. NoSQL databases (MongoDB, Redis, DynamoDB) are schema-flexible, optimise for specific access patterns, and typically sacrifice full ACID guarantees for horizontal scalability. Use SQL when data relationships and consistency matter; NoSQL when flexibility and scale are the priority.
12What is CORS and how do you handle it in Node.js?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks frontend code from making requests to a different origin (domain/port) than the one that served the page. To allow it server-side, set Access-Control-Allow-Origin response headers. In Express, the cors package handles this: app.use(cors({ origin: 'https://yourfrontend.com' })).
13What is JWT and how is it used for authentication?
A JWT (JSON Web Token) is a compact, URL-safe token with three base64-encoded parts: header (algorithm), payload (claims like userId, role, expiry), and a signature. The server signs the token on login; the client stores it (httpOnly cookie or memory) and sends it with requests. The server verifies the signature without a database lookup, making JWTs stateless and scalable.
14What is connection pooling in databases?
Creating a new database connection for every request is expensive (TCP handshake, authentication, resource allocation). A connection pool maintains a set of pre-established connections that are reused across requests. Libraries like pg-pool (PostgreSQL) or Mongoose manage pools automatically. Set pool size based on your database's max connections and application concurrency.
15What is the purpose of package.json?
package.json is the manifest for a Node.js project. It records the project's name, version, entry point, scripts (npm run dev, npm test), dependencies (required at runtime), devDependencies (only for development/testing), and engines (Node.js version range). package-lock.json (or yarn.lock) locks exact dependency versions for reproducible installs across environments.
16How do you prevent a Node.js server from crashing?
Never let uncaught exceptions crash production silently: handle process.on('uncaughtException') and process.on('unhandledRejection'). Use a process manager like PM2 with automatic restarts. Add proper error handling in all async paths. Use a load balancer with health checks to route traffic away from crashed instances. Implement circuit breakers for calls to external services that may fail.
17What is rate limiting and why is it important?
Rate limiting restricts how many requests a client can make in a time window, protecting your API from abuse, brute-force attacks, and accidental overload. Implement with express-rate-limit (in-process, not for multi-instance), or Redis (shared state across instances) with sliding window or token bucket algorithms. Always rate limit auth endpoints, AI calls, and any expensive operation.
18What is the difference between authentication and authorisation?
Authentication verifies who you are (login — checking credentials to establish identity). Authorisation determines what you're allowed to do (checking permissions after identity is established). Example: authentication confirms you are a logged-in user; authorisation checks whether that user has admin rights. Both are necessary; failing to distinguish them is a common security mistake.
19What are environment variables and why do you use them?
Environment variables externalise configuration — API keys, database URLs, secrets — from source code. This prevents secrets from being committed to version control and allows the same codebase to run with different configs (dev, staging, production). In Node.js, access them via process.env.MY_VAR. Use a .env file (read by dotenv in dev) and never commit it to git.
20What is REST and what are its principles?
REST (Representational State Transfer) is an architectural style for APIs. Its principles: stateless (each request contains all info needed), client-server separation, uniform interface (standard HTTP methods: GET, POST, PUT, PATCH, DELETE), resource-based URLs (/users/123 not /getUser), and cacheable responses. A RESTful API uses status codes correctly (200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error).
Level up your prep
Get company-specific questions for your interview
Upload your resume → get questions tailored to Google, Amazon, TCS, and 50+ companies.
Try AI Interview Prep →
© 2025 CareerLens · Home · Interview Questions · Pricing