Intermediate Node.js Interview Q&A
Are you preparing for a Node.js interview? Whether you are a beginner or looking to refresh your knowledge, this page covers Intermediate Node.js questions that are commonly asked in interviews.
How does the Event Loop work in Node.js?
The Event Loop in Node.js is responsible for handling asynchronous operations. It consists of six phases:
- Timers Phase → Executes
setTimeout()andsetInterval()callbacks. - Pending Callbacks → Executes system-related callbacks (e.g., TCP errors).
- Idle, Prepare → Internal use only.
- Poll Phase → Retrieves new I/O events, executes I/O callbacks.
- Check Phase → Executes
setImmediate()callbacks. - Close Callbacks → Executes
closeevent callbacks (e.g.,socket.on('close')).
What are Streams in Node.js?
Streams are objects that allow reading/writing data in chunks instead of loading everything into memory.
Types of streams:
- Readable Streams → Read data (
fs.createReadStream()). - Writable Streams → Write data (
fs.createWriteStream()). - Duplex Streams → Both read and write (
net.Socket). - Transform Streams → Modify data (
zlib.createGzip()).
What is the difference between spawn(), exec(), and fork()?
| Method | Description | Use Case |
|---|
spawn() | Executes a command and streams the output | Large data, real-time processing |
exec() | Executes a command and returns output in a buffer | Small data, easy handling |
fork() | Creates a new child process (IPC enabled) | Node.js process communication |
What is Middleware in Express.js?
Middleware functions in Express.js are functions that execute during the request-response cycle.
Types of Middleware:
- Application-level Middleware →
app.use() - Router-level Middleware →
router.use() - Built-in Middleware →
express.json(), express.static() - Error-handling Middleware →
app.use((err, req, res, next) => {})
What is CORS and how do you enable it in Express.js?
CORS (Cross-Origin Resource Sharing) allows requests from different origins.
To enable CORS in Express:
javascriptCopyEditconst cors = require('cors');
app.use(cors());
For more control:
javascriptCopyEditapp.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}));How does authentication work in Node.js?
Authentication methods:
- JWT (JSON Web Token) → Stateless token-based authentication.
- OAuth → Authentication via third-party providers (Google, Facebook).
- Session-based → Uses
express-sessionto store user sessions.
JWT Example:
javascriptCopyEditconst jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secretkey', { expiresIn: '1h' });
console.log(token);
const decoded = jwt.verify(token, 'secretkey');
console.log(decoded);How do you handle file uploads in Node.js?
Use multer for handling file uploads in Express.js.
Example:
javascriptCopyEditconst express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully!');
});
app.listen(3000);
What are Worker Threads in Node.js?
The worker_threads module allows executing JavaScript code in multiple threads, improving performance for CPU-intensive tasks.
Example:
javascriptCopyEditconst { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.postMessage('Hello');
worker.on('message', (msg) => {
console.log('Message from worker:', msg);
});
worker.js:
javascriptCopyEditconst { parentPort } = require('worker_threads');
parentPort.on('message', (msg) => {
parentPort.postMessage(`Received: ${msg}`);
});What is the purpose of the cluster module?
The cluster module enables multi-core processing by creating child processes.
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello, World!');
}).listen(8000);
}
What is the difference between PUT and PATCH in REST API?
| Method | Purpose | Example |
|---|
PUT | Updates the entire resource | { "name": "John", "age": 25 } |
PATCH | Updates specific fields | { "age": 26 } |
app.put('/user/:id', (req, res) => {
// Update entire user data
});
app.patch('/user/:id', (req, res) => {
// Update partial user data
});
