Prepare for your Node.js interview with these 30 essential questions covering basic, intermediate, and advanced topics. This guide is designed for freshers, candidates with 1-3 years of experience, and professionals with 3-6 years, helping you master Node.js concepts for roles at companies like Zoho, Paytm, Salesforce, Atlassian, and Swiggy.
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 Google’s V8 JavaScript engine. It uses an event-driven, non-blocking I/O model making it lightweight and efficient for building scalable network applications.[5]
2. Why is Node.js single-threaded?
Node.js uses a single thread for the event loop but achieves concurrency through asynchronous, non-blocking I/O operations. The libuv library handles background tasks on a thread pool, allowing efficient handling of thousands of concurrent connections.[5][7]
3. How do you create a basic HTTP server in Node.js?
Create a simple HTTP server using the built-in http module:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
This creates a server listening on port 3000 that responds with “Hello World”.[4]
4. What is the purpose of the npm command?
npm (Node Package Manager) is used to install, manage, and publish JavaScript packages. Common commands include npm init to initialize projects and npm install to add dependencies.[6]
5. What is an error-first callback in Node.js?
An error-first callback is a convention where the first parameter is an error object (or null if no error), followed by the result. Example:
fs.readFile('file.txt', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
[2]
6. What are the different types of modules in Node.js?
Node.js modules are categorized as:
- Core Modules: Built-in (http, fs, path)
- Local Modules: Custom modules created in your project
- Third-party Modules: Installed via npm
[4]
7. How do you create and export a custom module?
Create a module file math.js:
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
Use it in another file:
const math = require('./math');
console.log(math.add(5, 3)); // 8
[4][6]
8. What is the Event Loop in Node.js?
The Event Loop processes asynchronous callbacks in phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks. It enables non-blocking I/O by offloading tasks to the libuv thread pool.[3][5]
9. What is the difference between synchronous and asynchronous code in Node.js?
Synchronous code blocks execution until completion. Asynchronous code continues execution while waiting for I/O operations, using callbacks, promises, or async/await.[5]
10. How do you read a file asynchronously in Node.js?
Use the fs module with a callback:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
[1]
Intermediate Node.js Interview Questions (11-20)
11. What is Callback Hell and how to avoid it?
Callback hell occurs when multiple nested callbacks make code unreadable. Solutions include:
- Using Promises
- Async/await syntax
- Modularizing callbacks into named functions
[3][5]
12. What are Streams in Node.js?
Streams are objects that allow reading or writing data in chunks. Types include:
- Readable – for reading data
- Writable – for writing data
- Duplex – both reading and writing
- Transform – modifies data during processing
[3]
13. Explain the process.nextTick() method.
process.nextTick() queues a callback to execute at the end of the current operation, before the next event loop iteration. It’s higher priority than regular callbacks.[2]
14. What is the purpose of the cluster module?
The cluster module enables load balancing across multiple CPU cores by creating worker processes:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
} else {
// Workers start servers
http.createServer().listen(8000);
}
[4]
15. How does Node.js handle child processes?
The child_process module's fork() method creates a new Node.js process for CPU-intensive tasks, enabling true parallelism:
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => console.log(msg));
[5]
16. What are the different types of errors in Node.js?
Operational errors: Expected runtime errors (file not found, network issues). Programmer errors: Bugs in code logic that should be fixed.[2]
17. How do you handle uncaught exceptions in Node.js?
Use process.on('uncaughtException') for synchronous code errors:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
For async errors, use domains or proper promise rejection handling.[1]
18. What is the Buffer class in Node.js?
Buffer handles raw binary data. It's used for encoding/decoding binary data to strings:
const buf = Buffer.from('Hello');
console.log(buf.toString('hex')); // 48656c6c6f
[1]
19. Explain the Timers module in Node.js.
The Timers module provides functions like setTimeout(), setInterval(), setImmediate(), and clearTimeout() for scheduling code execution.[5]
20. How do you debug a Node.js application?
Use Node.js built-in debugger with node --inspect app.js or --inspect-brk for breakpoints. Chrome DevTools connects via chrome://inspect.[1]
Advanced Node.js Interview Questions (21-30)
21. What is the difference between setImmediate() and setTimeout()?
setImmediate() executes after the current poll phase, while setTimeout(fn, 0) waits for the next timer phase. setImmediate() has higher priority in I/O callbacks.[3]
22. Explain the V8 JavaScript engine's role in Node.js.
V8 compiles JavaScript directly to native machine code using just-in-time (JIT) compilation, enabling high performance without traditional parsing steps.[5]
23. How does Node.js handle DNS resolution?
The dns module provides asynchronous DNS resolution:
const dns = require('dns');
dns.resolve4('www.google.com', (err, addresses) => {
if (err) throw err;
console.log(addresses);
});
[1]
24. What are Worker Threads in Node.js?
Worker Threads (introduced in Node.js 10.5.0) enable running JavaScript in parallel threads for CPU-intensive tasks, unlike the single-threaded event loop:
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
new Worker(__filename);
} else {
// Worker code
}
[1]
25. How do you implement request throttling in Node.js?
Use a rate limiter tracking requests per IP:
const rateLimit = new Map();
app.use((req, res, next) => {
const ip = req.ip;
const now = Date.now();
if (!rateLimit.has(ip)) rateLimit.set(ip, []);
// Implementation logic
next();
});
[1]
26. What is the purpose of the domain module?
The domain module (deprecated) provided a way to handle uncaught exceptions in async code by associating errors with specific domains. Modern alternatives use async_hooks.[1]
27. Explain backpressure in Node.js streams.
Backpressure occurs when a stream writes data faster than it can be consumed. Handle it using stream.pipe() or checking writable.write() return value.[1]
28. How do you create a custom EventEmitter?
Extend the EventEmitter class:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => console.log('Event fired'));
myEmitter.emit('event');
[1]
29. What is the --max-old-space-size flag?
This V8 flag limits heap memory usage (in MB). Use node --max-old-space-size=4096 app.js to limit to 4GB heap size, preventing memory exhaustion.[1]
30. How do you handle graceful shutdown in Node.js?
Capture process signals and close resources:
process.on('SIGTERM', () => {
server.close(() => {
console.log('Process terminated');
});
});
This ensures databases, files, and servers close properly before exit.[1]