Node.js Interview Questions
Browse through our curated collection of questions
What is CORS and how do you handle it?
MediumCORS (Cross-Origin Resource Sharing) is like a security guard that controls which websites can access your API. By default, browsers block requests from different domains.
const express = require('express'); const cors = require('cors'); const app = express(); // Enable CORS for all routes app.use(cors()); // Or configure specific origins app.use(cors({ origin: ['http://localhost:3000', 'https://mywebsite.com'], methods: ['GET', 'POST'], credentials: true })); app.get('/api/data', (req, res) => { res.json({ message: 'This API can be accessed from allowed origins' }); });
How do you handle errors in Node.js?
MediumError handling is like having a safety net. You catch errors before they crash your application.
// Try-catch for synchronous code try { const data = JSON.parse('invalid json'); } catch (error) { console.log('Error parsing JSON:', error.message); } // Error handling in async/await async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } catch (error) { console.log('Error fetching data:', error.message); throw error; } } // Global error handler process.on('uncaughtException', (error) => { console.log('Uncaught Exception:', error); process.exit(1); });
What is the difference between process.nextTick() and setImmediate()?
MediumBoth schedule functions to run later, but at different times:
- process.nextTick(): Runs before any other asynchronous operation
- setImmediate(): Runs after I/O events
console.log('Start'); setImmediate(() => { console.log('setImmediate'); }); process.nextTick(() => { console.log('nextTick'); }); console.log('End'); // Output: // Start // End // nextTick // setImmediate
What is Clustering in Node.js?
MediumClustering is like having multiple workers doing the same job. If one worker gets busy, others can handle new requests.
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Create worker processes for (let i = 0; i < numCPUs; i++) { cluster.fork(); } } else { // Worker process http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker process'); }).listen(3000); }
What are Streams in Node.js?
MediumStreams are like water flowing through a pipe. Instead of loading entire large files into memory, streams process data piece by piece.
const fs = require('fs'); // Reading large file using streams const readStream = fs.createReadStream('large-file.txt'); const writeStream = fs.createWriteStream('copy-file.txt'); readStream.pipe(writeStream); readStream.on('data', (chunk) => { console.log('Received chunk of data'); });
What is Buffer in Node.js?
MediumBuffer is used to handle binary data (like images, videos, or files). Think of it as a temporary storage area for raw data.
// Create a buffer const buf = Buffer.from('Hello World', 'utf8'); console.log(buf); // <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64> // Convert back to string console.log(buf.toString()); // Hello World
What is the difference between dependencies and devDependencies?
Easy- dependencies: Packages your app needs to run (like Express for a web server)
- devDependencies: Packages you only need during development (like testing tools)
Real-life example: Dependencies are like the engine in your car (needed to drive), devDependencies are like the tools in your garage (only needed for maintenance).
{ "dependencies": { "express": "^4.18.0" }, "devDependencies": { "nodemon": "^2.0.15", "jest": "^27.5.0" } }
What is package.json?
Easypackage.json is like an ID card for your Node.js project. It contains information about your project and lists all the external packages your project needs.
{ "name": "my-awesome-app", "version": "1.0.0", "description": "My first Node.js app", "main": "app.js", "scripts": { "start": "node app.js", "dev": "nodemon app.js" }, "dependencies": { "express": "^4.18.0" } }
What is the difference between require() and import?
Easy- require() is the old way (CommonJS)
- import is the new way (ES6 modules)
// Using require() - CommonJS const express = require('express'); const { add } = require('./math'); // Using import - ES6 modules import express from 'express'; import { add } from './math.js';
What is Middleware?
MediumMiddleware is like security checkpoints at an airport. Every request passes through these checkpoints before reaching its final destination.
// Logging middleware app.use((req, res, next) => { console.log(`${req.method} ${req.url} - ${new Date()}`); next(); // Pass control to next middleware }); // Authentication middleware app.use('/admin', (req, res, next) => { if (req.headers.authorization) { next(); // User is authorized } else { res.status(401).send('Please login first'); } });