Top 50 Node.js Interview Questions & Answers for 2025
Comprehensive guide to Node.js interview questions covering fundamentals, advanced concepts, and real-world scenarios asked at top tech companies.
Node.js remains one of the most in-demand backend technologies in 2025. Whether you're preparing for your first Node.js role or aiming for a senior position at a FAANG company, this comprehensive guide covers the questions you'll encounter.
Fundamental Node.js Questions (1-15)
1. What is Node.js and why is it used?
Node.js is a JavaScript runtime built on Chrome's V8 engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient for building scalable network applications. Key use cases include REST APIs, real-time applications, microservices, and server-side rendering.
2. Explain the Event Loop in Node.js
The Event Loop is the core of Node.js async architecture. It continuously checks the call stack and callback queue, executing callbacks when the stack is empty. The loop has phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks.
// Event Loop Example
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Output: Start, End, Promise, Timeout3. What is the difference between process.nextTick() and setImmediate()?
process.nextTick() executes before the event loop continues (microtask queue), while setImmediate() executes in the check phase of the next event loop iteration. nextTick has higher priority and can starve the event loop if used recursively.
4. How does Node.js handle child processes?
Node.js provides the child_process module with methods like spawn(), exec(), execFile(), and fork(). spawn() is best for long-running processes with large data output, while exec() buffers output and is better for short commands.
5. Explain Streams in Node.js
Streams are collections of data that might not be available all at once. They enable processing data piece by piece, reducing memory usage. Types include Readable, Writable, Duplex, and Transform streams.
// Stream Example
const fs = require('fs');
const readStream = fs.createReadStream('large-file.txt');
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
readStream.on('end', () => console.log('Done!'));6. What is the purpose of package.json?
package.json is the manifest file containing project metadata, dependencies, scripts, and configuration. It enables reproducible builds through version locking and defines the project entry point, scripts, and npm configuration.
7. Explain middleware in Express.js
Middleware functions have access to the request, response, and next middleware function. They can execute code, modify req/res objects, end the request-response cycle, or call the next middleware. Common uses include authentication, logging, and error handling.
// Middleware Example
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Verify token...
next();
};
app.use('/api', authMiddleware);8. What is clustering in Node.js?
Clustering allows Node.js to utilize multiple CPU cores by creating child processes that share the same server port. The cluster module enables load balancing across workers, improving application throughput and reliability.
9. How do you handle errors in Node.js?
Error handling strategies include: try-catch for sync code, .catch() for promises, error-first callbacks, domain module (deprecated), process.on("uncaughtException"), and centralized error handling middleware in Express.
10. What is the Buffer class in Node.js?
Buffer is a class for handling binary data directly. It represents fixed-length sequences of bytes and is essential for working with streams, file systems, and network protocols. Buffers exist outside the V8 heap.
Intermediate Node.js Questions (16-30)
11. Explain the difference between CommonJS and ES Modules
CommonJS uses require() and module.exports (synchronous, dynamic), while ES Modules use import/export (static, supports tree-shaking). Node.js supports both, with ESM being the modern standard. Use .mjs extension or "type": "module" in package.json for ESM.
12. What is the Worker Threads module?
Worker Threads enable true multi-threading in Node.js for CPU-intensive tasks without blocking the main event loop. Unlike child processes, workers share memory through SharedArrayBuffer and can transfer data efficiently.
13. How do you implement rate limiting in Node.js?
// Rate Limiting with express-rate-limit
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per window
message: 'Too many requests, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api', limiter);14. What are Promises and how do they work?
Promises represent the eventual completion or failure of an async operation. They have three states: pending, fulfilled, and rejected. Promises enable chaining with .then() and .catch(), and can be composed with Promise.all(), Promise.race(), Promise.allSettled().
15. Explain async/await in Node.js
async/await is syntactic sugar over Promises, making async code look synchronous. async functions always return a Promise, and await pauses execution until the Promise resolves. Error handling uses try-catch blocks.
Advanced Node.js Questions (31-50)
16. How do you implement graceful shutdown in Node.js?
// Graceful Shutdown
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
async function gracefulShutdown(signal) {
console.log(`Received ${signal}. Shutting down gracefully...`);
// Stop accepting new connections
server.close(() => {
console.log('HTTP server closed');
});
// Close database connections
await mongoose.connection.close();
// Close Redis connections
await redisClient.quit();
process.exit(0);
}17. What is memory leak and how do you detect it in Node.js?
Memory leaks occur when memory is allocated but not released. Common causes include global variables, closures, event listeners, and caching. Detection tools include Node.js --inspect flag, Chrome DevTools, clinic.js, and memwatch-next.
18. Explain the V8 garbage collection process
V8 uses generational garbage collection with young generation (Scavenge algorithm) and old generation (Mark-Sweep-Compact). Objects start in young generation and are promoted to old generation if they survive multiple GC cycles.
19. How do you secure a Node.js application?
Key security practices:
- Use helmet.js for HTTP headers security
- Implement rate limiting and CORS
- Validate and sanitize all inputs
- Use parameterized queries (prevent SQL injection)
- Store secrets in environment variables
- Keep dependencies updated (npm audit)
- Implement proper authentication/authorization
- Use HTTPS and secure cookies
20. What is the N+1 query problem and how do you solve it?
N+1 occurs when fetching related data requires 1 query for the parent + N queries for each child. Solutions include eager loading (populate in Mongoose, include in Sequelize), batching with DataLoader, or using GraphQL with proper resolvers.
Practice these questions with our AI Mock Interview for Node.js. Get real-time feedback and improve your answers before your actual interview.
Practice with AI Mock Interviews
Put your knowledge to the test with our AI interviewer.