Prepare for your Node.js interview with this comprehensive guide featuring 30 essential questions and answers. Covering basic, intermediate, and advanced topics, these questions help freshers, candidates with 1-3 years of experience, and professionals with 3-6 years of experience master Node.js concepts, practical implementations, and real-world scenarios.
Basic Node.js Interview Questions (1-10)
1. What is Node.js?
Node.js is a runtime environment that allows JavaScript to run on the server-side using the V8 JavaScript engine. It enables building scalable network applications through its event-driven, non-blocking I/O model.
console.log('Hello from Node.js');
2. Why is Node.js single-threaded?
Node.js uses a single thread for the event loop to handle concurrent operations efficiently through non-blocking I/O. This design excels in I/O-intensive applications like web servers, avoiding the overhead of context switching in multi-threaded models.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Single-threaded handling');
});
server.listen(3000);
3. What is the Event Loop in Node.js?
The Event Loop is a mechanism that allows Node.js to perform non-blocking tasks. It continuously checks the call stack and task queues to execute callbacks, timers, and microtasks in phases like timers, I/O callbacks, and poll.
setTimeout(() => console.log('Timer'), 0);
Promise.resolve().then(() => console.log('Promise'));
4. Explain non-blocking I/O in Node.js.
Non-blocking I/O allows Node.js to handle operations asynchronously without waiting for completion. The main thread delegates I/O tasks to the libuv thread pool, processing other requests in the meantime for better performance.
const fs = require('fs');
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
5. What is an error-first callback in Node.js?
An error-first callback is a Node.js convention where the first parameter is an error object (null if no error), followed by the result. This pattern ensures consistent asynchronous error handling.
fs.readFile('file.txt', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
6. How do you create a simple HTTP server in Node.js?
Use the built-in http module’s createServer method to handle requests and start listening on a port.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000);
7. What is npm in Node.js?
npm (Node Package Manager) is the default package manager for Node.js. It handles installing, managing, and publishing packages defined in package.json.
npm init -y
npm install express
8. What is package.json?
package.json is a manifest file that contains project metadata, dependencies, scripts, and configuration. It enables reproducible installations with npm install.
{
"name": "my-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.0"
}
}
9. What are the benefits of using Node.js for I/O-heavy applications?
Node.js excels in I/O-heavy apps due to its non-blocking model, handling thousands of concurrent connections efficiently on a single thread, ideal for APIs and real-time services at companies like Paytm.
10. How do you handle synchronous vs asynchronous code in Node.js?
Synchronous code blocks execution until completion (use sparingly), while asynchronous code continues execution and handles results via callbacks, Promises, or async/await for scalability.
// Sync
const data = fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt', (err, data) => {});
Intermediate Node.js Interview Questions (11-20)
11. What is callback hell and how to avoid it?
Callback hell occurs with deeply nested callbacks, making code hard to read. Avoid it using Promises, async/await, or modular functions.
// Callback hell
fs.readFile(file1, (err, data1) => {
fs.readFile(file2, (err, data2) => { /* nested */ });
});
// Better: async/await
const data1 = await fs.promises.readFile(file1);
12. Explain Promises in Node.js.
Promises represent asynchronous operations with states: pending, fulfilled, or rejected. They chain operations cleanly compared to callbacks.
const promise = new Promise((resolve, reject) => {
resolve('Success');
});
promise.then(result => console.log(result));
13. What is async/await in Node.js?
async/await is syntactic sugar over Promises, making asynchronous code look synchronous. Use async functions and await for Promise resolution.
async function fetchData() {
try {
const data = await fs.promises.readFile('file.txt');
return data;
} catch (err) {
console.error(err);
}
}
14. What are Streams in Node.js?
Streams are objects for handling data in chunks, ideal for large files or network data. Types include Readable, Writable, Duplex, and Transform.
const fs = require('fs');
const readStream = fs.createReadStream('largefile.txt');
readStream.on('data', chunk => console.log(chunk));
15. How do you use environment variables in Node.js?
Environment variables store configuration data securely. Access them via process.env, often loaded with dotenv for development.
require('dotenv').config();
const port = process.env.PORT || 3000;
server.listen(port);
16. What is the cluster module in Node.js?
The cluster module enables load balancing across CPU cores by forking worker processes, improving performance for multi-core systems.
const cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
} else {
// Worker processes
http.createServer().listen(8000);
}
17. Explain the child_process fork() method.
fork() spawns a new Node.js process for CPU-intensive tasks, enabling communication via IPC channels for better resource utilization.
const { fork } = require('child_process');
const child = fork('worker.js');
child.on('message', msg => console.log(msg));
18. What is the difference between setImmediate() and setTimeout()?
setImmediate() executes after the current poll phase, while setTimeout() waits a specified delay. setImmediate() runs sooner in I/O contexts.
setTimeout(() => console.log('Timeout'), 0);
setImmediate(() => console.log('Immediate'));
19. How do you handle errors in asynchronous code at Zoho?
Use try/catch with async/await, .catch() on Promises, or error-first callbacks. Centralized error handlers prevent unhandled rejections.
async function safeOp() {
try {
await someAsync();
} catch (error) {
console.error('Handled:', error);
}
}
20. What are Buffers in Node.js?
Buffers handle raw binary data outside the V8 heap, useful for encoding/decoding binary streams like images or files.
const buf = Buffer.from('Hello');
console.log(buf.toString('hex'));
Advanced Node.js Interview Questions (21-30)
21. Explain process.nextTick() vs setImmediate().
process.nextTick() queues before the next event loop iteration (microtask), while setImmediate() queues in the check phase. nextTick() has higher priority.
process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('setImmediate'));
22. How does Node.js handle memory management?
Node.js uses V8’s garbage collector with generational collection (young/old space). Monitor with process.memoryUsage() and avoid leaks via closures.
console.log(process.memoryUsage());
23. What are the phases of the Node.js Event Loop?
Phases include timers, pending callbacks, idle/prepare, poll, check, and close callbacks, processing tasks in order for non-blocking execution.
24. Scenario: How would you scale a Node.js API for high traffic at Salesforce?
Use clustering for multi-core utilization, PM2 for process management, load balancers, and horizontal scaling across multiple instances with Redis caching.
25. Explain operational vs programmer errors in Node.js.
Operational errors are runtime issues like network failures (handle with retries). Programmer errors are bugs like syntax issues (crash and restart).
process.on('uncaughtException', err => {
console.error('Programmer error:', err);
});
26. How do you implement graceful shutdown in Node.js?
Listen for SIGTERM/SIGINT, close servers, finish pending requests, and exit cleanly to prevent data loss.
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});
27. What is the libuv library in Node.js?
libuv provides asynchronous I/O via a thread pool for operations like file system and DNS, enabling Node.js’s non-blocking capabilities on various platforms.
28. Scenario: Debug a memory leak in a long-running Node.js process at Atlassian.
Profile with –inspect, use heap snapshots in Chrome DevTools, track with clinic.js or heapdump, identify retainers like global variables or unclosed timers.
29. How do you secure a Node.js application?
Validate inputs, use helmet for headers, rate limiting, HTTPS, environment secrets, and avoid eval(). Regularly update dependencies with npm audit.
30. Explain backpressure in Node.js Streams at Adobe.
Backpressure occurs when writing faster than reading. Handle by pausing readable streams or using flow control in Transform streams to prevent memory overload.
readable.on('data', chunk => {
if (!writable.write(chunk)) readable.pause();
});