Resume Era - Professional Resume Builder

Node JS Interview Questions 2026: Complete Guide for Indian Developers (Freshers to Advanced)

Published 09 Feb 2026

Namaste developers! Agar aap Node.js interview ki taiyari kar rahe hain, toh yeh comprehensive guide aapke liye hai. Main 4+ saal se Indian IT industry mein kaam kar raha hoon - Bangalore, Pune, Hyderabad mein 40+ Node.js interviews De chuka hoon. Is article mein maine real interview experience ke basis pe node js interview questions collect kiye hain jo actually puche jaate hain.

Node.js abhi India ki top companies - Zomato, Swiggy, Paytm, Razorpay, Flipkart, CRED - sabhi mein use ho raha hai. Freshers ko 4-8 LPA mil raha hai, mid-level developers 10-18 LPA kama rahe hain, aur senior developers 20-40 LPA+ earn kar rahe hain. But competition bhi tough hai, isliye proper preparation zaroori hai.

Yeh Article Kiske Liye Hai?

  • College Freshers (0-1 year): First Node.js job ke liye prepare ho rahe ho

  • Mid-Level Developers (1-3 years): Better role ya company switch karna chahte ho

  • Experienced Professionals (3+ years): Senior/Lead/Architect positions target kar rahe ho

  • Career Switchers: PHP, Python, Java se Node.js mein shift ho rahe ho

Is Guide Mein Kya Milega?

  • 50+ real node js interview questions and answers with code examples

  • Freshers se lekar advanced level tak complete coverage

  • Scenario-based practical problems with solutions

  • Node js coding interview questions with clean implementations

  • Common mistakes aur unse kaise bache

  • Indian job market specific interview tips

Interview ke saath-saath apna resume bhi ready rakhna bahut important hai. ATS-friendly resume format follow karke apna tech industry resume banao jo recruiters ko impress kare.


Table of Contents

  1. Node JS Interview Questions for Freshers (0-1 Year)

  2. Intermediate Node JS Interview Questions (1-3 Years)

  3. Advanced Node JS Interview Questions (3+ Years)

  4. Scenario-Based Interview Questions

  5. Node JS Coding Interview Questions

  6. Common Mistakes Candidates Make

  7. Interview Preparation Tips (Indian Job Market)

  8. Frequently Asked Questions (FAQs)

  9. Conclusion


Node JS Interview Questions for Freshers (0-1 Year)

Freshers ke liye yeh basic node js interview questions for freshers zaroori hain. Agar aap college se nikle ho ya first job dhundh rahe ho, toh in concepts ko thoroughly samajh lo.

Q1: Node.js Kya Hai? JavaScript se Kaise Different Hai?

Answer:

Node.js ek JavaScript runtime environment hai jo Chrome ke V8 engine pe built hai. JavaScript originally sirf browsers mein run hoti thi (client-side), but Node.js ne JavaScript ko server-side pe run karna possible bana diya.

Key Differences:

JavaScript (Browser) Node.js (Server)
DOM manipulation kar sakte ho File system access kar sakte ho
Window object available hai Global object available hai
Frontend development Backend development
HTML/CSS ke saath kaam Database, APIs ke saath kaam

Simple Example:

// Browser JavaScript
document.getElementById('btn').addEventListener('click', () => {
    alert('Button clicked!');
});
// Node.js
const fs =require('fs');
const data = fs.readFileSync('file.txt','utf8');
console.log(data);

Real-World Use Case:

Swiggy ka backend Node.js mein hai. Jab aap order place karte ho, Node.js server restaurant ko notification bhejta hai, payment process karta hai, aur delivery tracking manage karta hai.

Q2: Node.js Kaise Kaam Karta Hai? Architecture Explain Karo

Answer:

Node.js single-threaded hai but asynchronous aur non-blocking hai. Iska matlab hai ki ek hi thread sab kuch manage karta hai, but operations background mein parallel chalta hai.

Node.js Architecture Components:

  1. V8 Engine : JavaScript code ko machine code mein convert karta hai

  2. libuv : C++ library jo asynchronous I/O operations handle karti hai

  3. Event Loop : Sab asynchronous operations ko manage karta hai

  4. Thread Pool : Heavy tasks (file I/O, crypto) ke liye separate threads

Visual Flow:

Request → Event Loop → Non-blocking I/O Operation

                ↓

         Callback Queue

                ↓

         Execute Callback → Response

Real Example:

console.log('1. Start');
setTimeout(()=>{
  console.log('3. Timeout callback');
},0);
console.log('2. End');
// Output:
// 1. Start
// 2. End
// 3. Timeout callback

Explanation: setTimeout asynchronous hai, toh JavaScript pehle synchronous code execute karta hai ( console.log('2. End') ), phir callback queue se timeout callback execute hota hai.

Q3: Event Loop Kya Hai? (Basic Level)

Answer:

Event Loop Node.js ka heart hai. Yeh continuously check karta rehta hai ki koi callback execute karna hai ya nahi. Jab bhi koi asynchronous operation complete hota hai (file read, database query, API call), uska callback event loop execute karta hai.

Event Loop Phases (Simple):

  1. Timers : setTimeout() aur setInterval() callbacks

  2. I/O Callbacks : File read, network requests ke callbacks

  3. Poll : New I/O events check karta hai

  4. Check : setImmediate() callbacks

  5. Close : Connection close events

Code Example:

const fs =require('fs');
console.log('Start');
fs.readFile('data.txt','utf8',(err, data)=>{
if(err)throw err;
  
console.log('File content:', data);
});
console.log('End');
// Output:
// Start
// End
// File content: [file ka data]

Real-World Analogy:

Imagine ek restaurant. Waiter (event loop) orders le raha hai, kitchen (background threads) khana bana rahi hai. Waiter orders lene ke baad wait nahi karta - next customer ke paas chala jata hai. Jab khana ready ho jata hai, waiter (event loop) usko serve karta hai.

Q4: Blocking vs Non-Blocking I/O - Difference Samjhao

Answer:

Blocking I/O : Code execution ruk jata hai jab tak operation complete na ho. Server ko wait karna padta hai.

Non-Blocking I/O : Code execution continue rehta hai. Operation background mein hota hai, callback ke through result milta hai.

const fs =require('fs');
// ❌ BLOCKING (Synchronous) - BAD for servers
console.log('Before read');
const data = fs.readFileSync('large-file.txt','utf8');// Yahan wait karega
console.log(data);
console.log('After read');
// ✅ NON-BLOCKING (Asynchronous) - GOOD for servers
console.log('Before read');
fs.readFile('large-file.txt','utf8',(err, data)=>{
if(err)throw err;
  
console.log(data);
});
console.log('After read');// Pehle yeh execute hoga
// Output (Non-blocking):
// Before read
// After read
// [file content]

Production Impact:

Agar aap blocking I/O use karte ho production mein, toh ek request process hone tak doosri requests wait karenge. 1000 users ki requests aayengi toh server hang ho jayega. Non-blocking I/O se sabhi requests parallel process hote hain.

Q5: NPM Kya Hai? Package.json Ka Role?

Answer:

NPM (Node Package Manager) duniya ka largest software registry hai. Yeh Node.js ka default package manager hai jisse hum third-party libraries install kar sakte hain.

Package.json : Yeh project ka configuration file hai jo:

  • Project metadata store karta hai

  • Dependencies list karta hai

  • Scripts define karta hai

  • Project version manage karta hai

Package.json Example:

{
"name":"my-node-app",
"version":"1.0.0",
"description":"Node.js backend application",
"main":"server.js",
"scripts":{
"start":"node server.js",
"dev":"nodemon server.js",
"test":"jest",
"build":"npm run clean && npm run compile"
},
"dependencies":{
"express":"^4.18.2",
"mongoose":"^7.0.3",
"dotenv":"^16.0.3"
},
"devDependencies":{
"nodemon":"^2.0.22",
"jest":"^29.5.0"
},
"engines":{
"node":">=16.0.0"
}
}

NPM Commands:

# Project initialize karo
npm init -y

# Package install karo
npminstall express

npm i mongoose

# Dev dependency install karo
npminstall --save-dev nodemon

# Specific version install karo
npminstall express@4.18.2

# Global package install karo
npminstall -g pm2

# Script run karo
npm start

npm run dev

# Dependencies update karo
npm update

# Package uninstall karo
npm uninstall express

Interview Tip:

Interviewer puchega - "dependencies aur devDependencies mein kya difference hai?"

Answer : Dependencies production mein zaroor hai (express, mongoose), devDependencies sirf development mein chahiye (nodemon, jest, eslint).

Q6: require() vs import - Kab Kya Use Karein?

Answer:

Yeh module system ke do alag tareeke hain. Node.js pehle sirf CommonJS (require) support karta tha, ab ES6 Modules (import) bhi support karta hai.

CommonJS (require) - Traditional:

// Export karo
// math.js
functionadd(a, b){
return a + b;
}
functionsubtract(a, b){
return a - b;
}
module.exports ={ add, subtract };
// Import karo
// app.js
const math =require('./math');
console.log(math.add(5,3));// 8
// Destructuring
const{ add, subtract }=require('./math');
console.log(add(10,5));// 15

ES6 Modules (import) - Modern:

// Export karo
// math.js
exportfunctionadd(a, b){
return a + b;
}
exportfunctionsubtract(a, b){
return a - b;
}
// Default export
exportdefaultfunctionmultiply(a, b){
return a * b;
}
// Import karo
// app.js
import multiply,{ add, subtract }from'./math.js';
console.log(add(5,3));// 8
console.log(multiply(4,2));// 8

ES6 Modules Enable Karne Ke Liye:

// package.json
{
"type":"module"
}

Ya file ko .mjs extension do.

Key Differences:

Feature require() import
Syntax CommonJS ES6
Loading Synchronous Asynchronous
Dynamic Import Anywhere Top level only
Default in Node Yes (v12 se pehle) Need "type": "module"
Tree Shaking No Yes

Production Recommendation:

Most Indian companies abhi bhi CommonJS ( require ) use kar rahi hain kyunki stable hai aur widely supported hai. But new projects ES6 modules adopt kar rahi hain.

Q7: Global Objects in Node.js - Kaunse Hain?

Answer:

Node.js mein kuch objects globally available hote hain without import kiye.

Common Global Objects:

// 1. __dirname - Current directory ka absolute path
console.log(__dirname);
// Output: /home/user/project
// 2. __filename - Current file ka absolute path
console.log(__filename);
// Output: /home/user/project/app.js
// 3. process - Current Node.js process ka info
console.log(process.version);// v18.12.0
console.log(process.platform);// linux, win32, darwin
console.log(process.env.NODE_ENV);// development, production
console.log(process.argv);// Command line arguments
// 4. console - Logging ke liye
console.log('Info message');
console.error('Error message');
console.warn('Warning message');
console.table([{name:'John',age:30}]);
// 5. setTimeout, setInterval, setImmediate
setTimeout(()=> console.log('After 1 second'),1000);
const interval =setInterval(()=>{
  console.log('Every 2 seconds');
},2000);
// Clear karne ke liye
clearInterval(interval);
setImmediate(()=> console.log('Immediate execution'));
// 6. Buffer - Binary data handle karne ke liye
const buf = Buffer.from('Hello Node.js');
console.log(buf);// <Buffer 48 65 6c 6c 6f ...>
console.log(buf.toString());// Hello Node.js
// 7. module and exports
console.log(module);
console.log(exports);

Interview Trick Question:

"Browser mein window object hai, Node.js mein kya hai?"

Answer : Node.js mein global object hai, but best practice hai explicitly import karna rather than global use karna.

Q8: Callback Functions Kya Hain? Callback Hell Kya Hai?

Answer:

Callback ek function hai jo doosre function ke argument mein pass hota hai aur baad mein execute hota hai.

Simple Callback Example:

functionfetchUser(userId, callback){
setTimeout(()=>{
const user ={id: userId,name:'Rahul'};
callback(null, user);
},1000);
}
// Use callback
fetchUser(123,(error, user)=>{
if(error){
    console.error(error);
}else{
    console.log('User:', user);
}
});

Callback Hell (Pyramid of Doom):

Jab multiple nested callbacks ho jaate hain, code unreadable ban jata hai.

// ❌ CALLBACK HELL - Bad Practice
getUser(userId,(err, user)=>{
if(err)throw err;
getOrders(user.id,(err, orders)=>{
if(err)throw err;
getOrderDetails(orders[0].id,(err, details)=>{
if(err)throw err;
getPaymentInfo(details.paymentId,(err, payment)=>{
if(err)throw err;
        console.log('Payment:', payment);
// Aur bhi nesting ho sakti hai...
});
});
});
});

Solution - Promises/Async-Await:

// ✅ MODERN APPROACH - Clean Code
asyncfunctiongetUserData(userId){
try{
const user =awaitgetUser(userId);
const orders =awaitgetOrders(user.id);
const details =awaitgetOrderDetails(orders[0].id);
const payment =awaitgetPaymentInfo(details.paymentId);
    console.log('Payment:', payment);
}catch(error){
    console.error('Error:', error);
}
}

Freshers ke liye yeh 8 questions bahut important hain. Apne fresher resume mein in concepts ko skills section mein zaroor mention karo: "Node.js fundamentals, Event Loop, Asynchronous programming, NPM, Module systems".


Intermediate Node JS Interview Questions (1-3 Years)

Agar aap 1-3 saal ka experience rakhte ho, toh interviewers expect karte hain ki aapne production applications pe kaam kiya hai. Yeh intermediate node js interview questions real-world scenarios pe based hain.

Q9: Event Loop ke Phases Detail Mein Explain Karo

Answer:

Event loop 6 phases mein kaam karta hai. Yeh senior-level interviews mein definitely puchha jata hai.

Detailed Event Loop Phases:

   ┌───────────────────────────┐

┌─>│           timers          │

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │     pending callbacks     │

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │       idle, prepare       │

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │           poll            │

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │           check           │

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

└──│      close callbacks      │

   └───────────────────────────┘

Phase-wise Explanation:

  1. Timers Phase : setTimeout() aur setInterval() ke callbacks execute hote hain

  2. Pending Callbacks : TCP errors jaise system operations

  3. Idle, Prepare : Internal use (interview mein skip kar sakte ho)

  4. Poll Phase : New I/O events retrieve aur execute karta hai (most important)

  5. Check Phase : setImmediate() callbacks execute hote hain

  6. Close Callbacks : socket.on('close') jaise events

Tricky Interview Code:

setTimeout(()=> console.log('setTimeout'),0);
setImmediate(()=> console.log('setImmediate'));
process.nextTick(()=> console.log('nextTick'));
Promise.resolve().then(()=> console.log('Promise'));
// Output:
// nextTick
// Promise
// setTimeout (ya setImmediate - depends on context)
// setImmediate (ya setTimeout)

Explanation:

process.nextTick() sabse pehle execute hota hai (current phase ke baad, next phase se pehle). Promises microtask queue mein jaate hain jo nextTick ke baad execute hote hain.

Q10: Call Stack, Callback Queue, aur Microtask Queue

Answer:

Node.js mein teen important queues hain jo execution order decide karte hain.

Components:

  1. Call Stack : Synchronous code execute hota hai (LIFO - Last In First Out)

  2. Microtask Queue : Promises, process.nextTick() - Higher Priority

  3. Callback Queue (Task Queue) : setTimeout , setInterval , I/O operations

Priority Order:

Call Stack > Microtask Queue > Callback Queue

Complete Example:

console.log('1. Call Stack - Start');
setTimeout(()=>{
  console.log('6. Callback Queue - setTimeout');
},0);
Promise.resolve()
.then(()=> console.log('4. Microtask - Promise 1'))
.then(()=> console.log('5. Microtask - Promise 2'));
process.nextTick(()=>{
  console.log('3. Microtask - nextTick');
});
console.log('2. Call Stack - End');
// Output:
// 1. Call Stack - Start
// 2. Call Stack - End
// 3. Microtask - nextTick
// 4. Microtask - Promise 1
// 5. Microtask - Promise 2
// 6. Callback Queue - setTimeout

Step-by-Step Execution:

  1. Synchronous code pehle execute hota hai (Call Stack)

  2. Call stack empty hone ke baad Microtask Queue check hota hai

  3. process.nextTick() sabse pehle (highest priority)

  4. Promises execute hote hain

  5. Last mein Callback Queue (setTimeout)

Production Pitfall:

// ❌ INFINITE LOOP - Server crash karega
functionrecursiveNextTick(){
  process.nextTick(recursiveNextTick);
}
recursiveNextTick();// DON'T DO THIS

Yeh code event loop ko block kar dega kyunki nextTick continuously microtask queue mein add hota rahega.

Q11: Promises vs Async/Await - Production Mein Kab Kya Use Karein?

Answer:

Dono hi asynchronous code handle karne ke tarike hain, but readability aur error handling mein difference hai.

Promises:

functiongetUserData(userId){
returnfetch(`/api/users/${userId}`)
.then(response=> response.json())
.then(user=>{
returnfetch(`/api/posts/${user.id}`);
})
.then(response=> response.json())
.then(posts=>{
return{ user, posts };
})
.catch(error=>{
      console.error('Error:', error);
throw error;
});
}
// Use
getUserData(123)
.then(data=> console.log(data))
.catch(err=> console.error(err));

Async/Await (Cleaner & Recommended):

asyncfunctiongetUserData(userId){
try{
const userResponse =awaitfetch(`/api/users/${userId}`);
const user =await userResponse.json();
const postsResponse =awaitfetch(`/api/posts/${user.id}`);
const posts =await postsResponse.json();
return{ user, posts };
}catch(error){
    console.error('Error:', error);
throw error;
}
}
// Use
try{
const data =awaitgetUserData(123);
  console.log(data);
}catch(err){
  console.error(err);
}

Parallel Execution - IMPORTANT!

// ❌ Sequential (Slow) - 3 seconds total
asyncfunctionslowFetch(){
const user =awaitfetchUser();// 1s wait
const posts =awaitfetchPosts();// 1s wait
const comments =awaitfetchComments();// 1s wait
return{ user, posts, comments };
}
// ✅ Parallel (Fast) - 1 second total
asyncfunctionfastFetch(){
const[user, posts, comments]=await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
]);
return{ user, posts, comments };
}
// Partial parallel execution
asyncfunctionsmartFetch(userId){
// User pehle chahiye
const user =awaitfetchUser(userId);
// Posts aur comments parallel fetch karo
const[posts, comments]=await Promise.all([
fetchPosts(user.id),
fetchComments(user.id)
]);
return{ user, posts, comments };
}

Error Handling Comparison:

// Promises mein multiple catch blocks
fetch('/api/data')
.then(res=> res.json())
.catch(err=> console.error('Network error:', err))
.then(data=>processData(data))
.catch(err=> console.error('Processing error:', err));
// Async/await mein centralized try-catch
asyncfunctionfetchData(){
try{
const res =awaitfetch('/api/data');
const data =await res.json();
returnprocessData(data);
}catch(error){
if(error.name ==='NetworkError'){
      console.error('Network issue');
}else{
      console.error('Processing failed');
}
throw error;
}
}

Q12: Streams aur Buffers - Real Production Use Cases

Answer:

Streams : Data ko chunks mein read/write karne ki facility. Large files ya real-time data handle karne ke liye perfect.

Buffers : Binary data ko temporarily store karta hai (images, videos, files).

Why Streams?

Imagine 2GB ki video file upload kar rahe ho. Agar poori file memory mein load karoge, server crash ho jayega. Streams se piece-by-piece process hota hai.

Types of Streams:

  1. Readable : Data read karte hain (file read, HTTP request)

  2. Writable : Data write karte hain (file write, HTTP response)

  3. Duplex : Read aur write dono (TCP socket)

  4. Transform : Data ko modify karke pass karte hain (compression, encryption)

Real Production Example:

const fs =require('fs');
const http =require('http');
// ❌ BAD APPROACH - Memory overflow
http.createServer((req, res)=>{
const data = fs.readFileSync('large-video.mp4');// 2GB file
  res.end(data);// Server crash possibility
}).listen(3000);
// ✅ GOOD APPROACH - Using Streams
http.createServer((req, res)=>{
const stream = fs.createReadStream('large-video.mp4');
  stream.pipe(res);// Memory efficient, chunk-by-chunk
}).listen(3000);

File Compression with Streams:

const fs =require('fs');
const zlib =require('zlib');
// Input file ko compress karke output file mein save karo
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())// Compress karo
.pipe(fs.createWriteStream('input.txt.gz'));
console.log('File compression started...');

Buffer Operations:

// String to Buffer
const buf1 = Buffer.from('Hello Node.js','utf8');
console.log(buf1);// <Buffer 48 65 6c 6c 6f ...>
console.log(buf1.toString());// Hello Node.js
// Specific size buffer create karo
const buf2 = Buffer.alloc(10);// 10 bytes
console.log(buf2);// <Buffer 00 00 00 00 00 00 00 00 00 00>
// Buffer operations
const buf3 = Buffer.from([1,2,3,4,5]);
console.log(buf3.length);// 5
console.log(buf3[0]);// 1
// Buffer concat
const buf4 = Buffer.concat([buf1, buf3]);
console.log(buf4.toString());

Real Interview Scenario:

"CSV file upload kar rahe ho jo 500MB ki hai. Kaise handle karoge?"

const fs =require('fs');
const readline =require('readline');
asyncfunctionprocessLargeCSV(filePath){
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay:Infinity
});
let lineCount =0;
forawait(const line of rl){
// Process each line
const data = line.split(',');
awaitsaveToDatabase(data);
    lineCount++;
if(lineCount %1000===0){
      console.log(`Processed ${lineCount} lines`);
}
}
  console.log(`Total lines processed: ${lineCount}`);
}
processLargeCSV('large-data.csv');

Q13: Error Handling Best Practices - Production Grade

Answer:

Production applications mein proper error handling critical hai. Ek error ki wajah se poora server crash nahi hona chahiye.

Synchronous Error Handling:

try{
const data =JSON.parse(invalidJSON);
processData(data);
}catch(error){
  console.error('JSON parse failed:', error.message);
// Log to monitoring service (Sentry, CloudWatch)
}

Asynchronous Error Handling:

// ❌ WRONG - Unhandled promise rejection
asyncfunctionfetchData(){
const data =awaitfetch('/api/data');// Agar fail ho?
return data.json();
}
// ✅ CORRECT - Proper error handling
asyncfunctionfetchData(){
try{
const response =awaitfetch('/api/data');
if(!response.ok){
thrownewError(`HTTP ${response.status}: ${response.statusText}`);
}
returnawait response.json();
}catch(error){
    console.error('Fetch failed:', error.message);
// Retry logic ya fallback data
throw error;// Re-throw for upstream handling
}
}

Global Error Handlers:

// Unhandled Promise Rejections
process.on('unhandledRejection',(reason, promise)=>{
  console.error('Unhandled Rejection at:', promise,'reason:', reason);
// Log to error tracking service
// DON'T exit in production immediately
});
// Uncaught Exceptions
process.on('uncaughtException',(error)=>{
  console.error('Uncaught Exception:', error);
// Log error
// Graceful shutdown
  process.exit(1);
});
// SIGTERM signal (for graceful shutdown)
process.on('SIGTERM',()=>{
  console.log('SIGTERM received, closing server...');
  server.close(()=>{
    console.log('Server closed');
    process.exit(0);
});
});

Custom Error Classes:

classAppErrorextendsError{
constructor(message, statusCode){
super(message);
this.statusCode = statusCode;
this.isOperational =true;
    Error.captureStackTrace(this,this.constructor);
}
}
classValidationErrorextendsAppError{
constructor(message){
super(message,400);
}
}
classNotFoundErrorextendsAppError{
constructor(message){
super(message,404);
}
}
// Usage
asyncfunctiongetUser(userId){
const user =await User.findById(userId);
if(!user){
thrownewNotFoundError('User not found');
}
return user;
}
// Express error handler
app.use((err, req, res, next)=>{
if(err.isOperational){
return res.status(err.statusCode).json({
status:'error',
message: err.message

});
}
// Programmer error - log and send generic message
  console.error('ERROR ?:', err);
  res.status(500).json({
status:'error',
message:'Something went wrong'
});
});

Q14: Environment Variables - Production Best Practices

Answer:

Environment variables se sensitive information (API keys, database URLs) code mein hardcode nahi karte. .env file use karte hain.

Setup:

npminstall dotenv

.env File:

# Server Configuration

PORT=5000

NODE_ENV=production

# Database

DB_HOST=localhost

DB_PORT=27017

DB_NAME=myapp_prod

DB_USER=admin

DB_PASSWORD=superSecretPassword123

# JWT

JWT_SECRET=your-256-bit-secret

JWT_EXPIRE=7d

# Third Party APIs

RAZORPAY_KEY_ID=rzp_test_xxxxx

RAZORPAY_KEY_SECRET=xxxxx

AWS_ACCESS_KEY=AKIA...

AWS_SECRET_KEY=xxxxx

# Email

SMTP_HOST=smtp.gmail.com

SMTP_PORT=587

SMTP_USER=youremail@gmail.com

SMTP_PASSWORD=your-app-password

Load in Application:

require('dotenv').config();
const config ={
port: process.env.PORT||3000,
env: process.env.NODE_ENV||'development',
database:{
host: process.env.DB_HOST,
port: process.env.DB_PORT,
name: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
},
jwt:{
secret: process.env.JWT_SECRET,
expire: process.env.JWT_EXPIRE
}
};
module.exports = config;

Different Environments:

// config.js
const development ={
port:3000,
db:'mongodb://localhost/dev_db',
logLevel:'debug'
};
const production ={
port: process.env.PORT,
db: process.env.DB_URI,
logLevel:'error'
};
const test ={
port:3001,
db:'mongodb://localhost/test_db',
logLevel:'silent'
};
const config ={
  development,
  production,
  test

};
module.exports = config[process.env.NODE_ENV||'development'];

Security Best Practices:

  1. .env file ko .gitignore mein add karo

  2. Production secrets ko environment mein directly set karo (never commit)

  3. .env.example file rakho (without actual values)

# .gitignore

node_modules/

.env

.env.local

.env.production
# .env.example

PORT=

NODE_ENV=

DB_URI=

JWT_SECRET=

Intermediate level questions mein key skills for resume mein yeh add karo: "Asynchronous programming, Streams, Error handling, Environment configuration, Production debugging".


Advanced Node JS Interview Questions (3+ Years)

Senior developers aur 3+ years experience wale professionals ke liye advanced node js interview questions . Yahan architecture, scalability, aur performance optimization pe focus hai.

Q15: Node.js Concurrency Kaise Handle Karta Hai?

Answer:

Node.js single-threaded hai but asynchronous non-blocking I/O aur event-driven architecture se concurrency achieve karta hai.

How It Works:

  1. Main Thread (Event Loop) : Single thread jo sabhi incoming requests handle karta hai

  2. Thread Pool (libuv) : Background mein 4 threads (default) heavy operations ke liye

  3. Asynchronous Operations : I/O operations blocking nahi karte

Visual Representation:

1000 Concurrent Requests

         ↓

    Event Loop (Single Thread)

         ↓

   Non-blocking Operations

         ↓

    Thread Pool (4 threads)

    [File I/O, Crypto, DNS]

         ↓

    Callback Queue

         ↓

    Responses sent

Production Example:

const http =require('http');
const server = http.createServer((req, res)=>{
// Yeh synchronous hai - FAST
const data ={message:'Hello',timestamp: Date.now()};
// Yeh asynchronous hai - thread pool mein jayega
require('crypto').pbkdf2('secret','salt',100000,64,'sha512',(err, key)=>{
if(err)throw err;
    res.end(JSON.stringify({ data,hash: key.toString('hex')}));
});
});
server.listen(3000);
// 1000 concurrent requests aaye toh?
// - Event loop sabko accept karega (non-blocking)
// - Heavy crypto operations thread pool mein jayenge
// - Responses parallel mein generate honge

Thread Pool Size Increase Karna:

// Default: 4 threads
// Increase kar sakte ho based on CPU cores
process.env.UV_THREADPOOL_SIZE=8;

Interview Answer Format:

"Node.js single-threaded hai event loop ke liye, but libuv library background mein thread pool maintain karti hai heavy operations ke liye. I/O operations non-blocking hain, toh ek request wait nahi karti doosri request ke liye. Yeh concurrency model high-throughput applications ke liye perfect hai jahan CPU-intensive kam aur I/O zyada ho."

Q16: Cluster Module vs Worker Threads - Kab Kya Use Karein?

Answer:

Dono hi Node.js ko scale karne ke tareeke hain, but different use cases ke liye.

Cluster Module - Multiple Processes:

const cluster =require('cluster');
const http =require('http');
const os =require('os');
const numCPUs = os.cpus().length;
if(cluster.isMaster){
  console.log(`Master process ${process.pid} is running`);
// Fork workers (CPU cores ke barabar)
for(let i =0; i < numCPUs; i++){
    cluster.fork();
}
  cluster.on('exit',(worker, code, signal)=>{
    console.log(`Worker ${worker.process.pid} died`);
    console.log('Starting a new worker...');
    cluster.fork();// Restart crashed worker
});
}else{
// Workers share TCP connection
  http.createServer((req, res)=>{
    res.writeHead(200);
    res.end(`Handled by worker ${process.pid}\n`);
}).listen(8000);
  console.log(`Worker ${process.pid} started`);
}

Worker Threads - CPU-Intensive Tasks:

const{ Worker, isMainThread, parentPort, workerData }=require('worker_threads');
if(isMainThread){
// Main thread
  console.log('Main thread starting...');
const worker =newWorker(__filename,{
workerData:{num:5}
});
  worker.on('message',(result)=>{
    console.log('Result from worker:', result);
});
  worker.on('error',(err)=>{
    console.error('Worker error:', err);
});
  worker.on('exit',(code)=>{
if(code !==0){
      console.error(`Worker stopped with exit code ${code}`);
}
});
}else{
// Worker thread
functionfibonacci(n){
if(n <=1)return n;
returnfibonacci(n -1)+fibonacci(n -2);
}
const result =fibonacci(workerData.num);
  parentPort.postMessage(result);
}

Comparison Table:

Feature Cluster Module Worker Threads
Purpose Multiple processes CPU-intensive tasks
Memory Separate memory space Shared memory
Communication IPC (Inter-Process) Message passing
Overhead High (process creation) Low (thread creation)
Use Case HTTP servers, load balancing Image processing, calculations
Crash Impact Other workers unaffected Can crash main thread

Real Production Scenario:

// Video encoding service
const{ Worker }=require('worker_threads');
const express =require('express');
const app =express();
app.post('/encode-video',async(req, res)=>{
const videoPath = req.body.videoPath;
// Heavy task ko worker thread mein bhejo
const worker =newWorker('./videoEncoder.js',{
workerData:{ videoPath }
});
  worker.on('message',(encodedPath)=>{
    res.json({success:true, encodedPath });
});
  worker.on('error',(err)=>{
    res.status(500).json({error: err.message });
});
});
app.listen(3000);

When to Use What:

  • Cluster : Web servers, API servers - multiple instances chahiye

  • Worker Threads : Image processing, video encoding, complex calculations

Q17: Memory Leaks in Node.js - Kaise Detect aur Fix Karein?

Answer:

Memory leak tab hota hai jab application memory occupy karti ja rahi hai but release nahi kar rahi. Eventually server crash ho jata hai.

Common Causes:

  1. Global Variables : Accidentally global scope mein variables

  2. Event Listeners : Remove nahi kiye

  3. Closures : Unnecessary references hold kar rahe hain

  4. Timers : setInterval clear nahi kiya

  5. Cache : Unlimited caching without eviction

Examples of Memory Leaks:

// ❌ LEAK 1: Global variable
functionprocessData(){
  data =[];// 'var' ya 'let' bhool gaye
for(let i =0; i <1000000; i++){
    data.push(i);
}
}
// ✅ FIX
functionprocessData(){
const data =[];// Local scope
for(let i =0; i <1000000; i++){
    data.push(i);
}
}// data garbage collected ho jayega
// ❌ LEAK 2: Event listeners not removed
const EventEmitter =require('events');
const emitter =newEventEmitter();
functionaddListener(){
  emitter.on('data',(data)=>{
    console.log(data);
});
}
// Baar baar call karne se listeners badhte jayenge
addListener();
addListener();
addListener();
// ✅ FIX
functionaddListener(){
  emitter.once('data',(data)=>{// 'once' use karo
    console.log(data);
});
}
// Ya explicitly remove karo
emitter.removeAllListeners('data');
// ❌ LEAK 3: setInterval not cleared
functionstartPolling(){
setInterval(()=>{
fetchDataFromAPI();
},1000);
}
// ✅ FIX
functionstartPolling(){
const intervalId =setInterval(()=>{
fetchDataFromAPI();
},1000);
// Cleanup function
return()=>clearInterval(intervalId);
}
const stopPolling =startPolling();
// Later...
stopPolling();
// ❌ LEAK 4: Unlimited cache
const cache ={};
functioncacheData(key, value){
  cache[key]= value;// Kabhi delete nahi hoga
}
// ✅ FIX: Use LRU cache
constLRU=require('lru-cache');
const cache =newLRU({
max:500,// Maximum 500 items
maxAge:1000*60*60// 1 hour
});

Memory Leak Detection Tools:

# Install tools
npminstall -g clinic

npminstall --save-dev memwatch-next

# Run with clinic
clinic doctor -- node app.js

# Or use built-in profiler
node --inspect app.js

# Open chrome://inspect

Production Monitoring:

// Memory usage tracking
setInterval(()=>{
const used = process.memoryUsage();
  console.log({
rss:`${Math.round(used.rss / 1024 / 1024)}MB`,// Total memory
heapTotal:`${Math.round(used.heapTotal / 1024 / 1024)}MB`,
heapUsed:`${Math.round(used.heapUsed / 1024 / 1024)}MB`,
external:`${Math.round(used.external / 1024 / 1024)}MB`
});
},5000);
// Heap dump on high memory
const heapdump =require('heapdump');
setInterval(()=>{
const heapUsed = process.memoryUsage().heapUsed /1024/1024;
if(heapUsed >500){// 500MB se zyada
    console.log('Taking heap dump...');
    heapdump.writeSnapshot((err, filename)=>{
      console.log('Heap dump written to', filename);
});
}
},60000);

Q18: Performance Optimization Techniques

Answer:

Production applications ko fast aur efficient banana critical hai. Yeh techniques actually Indian companies mein use hote hain.

1. Caching (Redis):

const redis =require('redis');
const client = redis.createClient();
// Cache middleware
constcache=(duration)=>{
returnasync(req, res, next)=>{
const key =`cache:${req.originalUrl}`;
    client.get(key,(err, data)=>{
if(err)throw err;
if(data){
return res.json(JSON.parse(data));// Cache hit
}
// Cache miss - modify res.json
      res.originalJson = res.json;
      res.json=(body)=>{
        client.setex(key, duration,JSON.stringify(body));
        res.originalJson(body);
};
next();
});
};
};
// Usage
app.get('/api/products',cache(300),async(req, res)=>{
const products =await Product.find();
  res.json(products);// Automatically cached for 5 minutes
});

2. Database Query Optimization:

// ❌ SLOW - Multiple queries
asyncfunctiongetUserWithPosts(userId){
const user =await User.findById(userId);
const posts =await Post.find({userId: user._id });
return{ user, posts };
}
// ✅ FAST - Single query with populate
asyncfunctiongetUserWithPosts(userId){
const user =await User.findById(userId)
.populate('posts')
.lean();// Plain JS object (faster than Mongoose document)
return user;
}
// Indexing
userSchema.index({email:1});
userSchema.index({createdAt:-1});
// Projection - only required fields
const users =await User.find({},'name email');// Sirf name aur email

3. Compression:

const compression =require('compression');
app.use(compression({
level:6,// Compression level (0-9)
threshold:1024,// Only compress if response > 1KB
filter:(req, res)=>{
if(req.headers['x-no-compression']){
returnfalse;
}
return compression.filter(req, res);
}
}));

4. Load Balancing (NGINX):

# /etc/nginx/nginx.conf

upstream nodejs_backend {

  least_conn; # Load balancing method

  server 127.0.0.1:3000;

  server 127.0.0.1:3001;

  server 127.0.0.1:3002;

  server 127.0.0.1:3003;

}

server {

  listen 80;

  location / {

    proxy_pass http://nodejs_backend;

    proxy_http_version 1.1;

    proxy_set_header Upgrade $http_upgrade;

    proxy_set_header Connection 'upgrade';

    proxy_set_header Host $host;

    proxy_cache_bypass $http_upgrade;

  }

}

5. Connection Pooling:

const mongoose =require('mongoose');
mongoose.connect(process.env.DB_URI,{
useNewUrlParser:true,
useUnifiedTopology:true,
poolSize:10,// Maintain 10 connections
socketTimeoutMS:45000,
family:4// Use IPv4
});

6. Asynchronous Operations:

// ❌ SLOW - Sequential
asyncfunctionprocessUsers(){
for(const user of users){
awaitsendEmail(user.email);// Wait for each
}
}
// ✅ FAST - Parallel
asyncfunctionprocessUsers(){
await Promise.all(
    users.map(user=>sendEmail(user.email))
);
}
// Batch processing
asyncfunctionprocessInBatches(items, batchSize, processor){
for(let i =0; i < items.length; i += batchSize){
const batch = items.slice(i, i + batchSize);
await Promise.all(batch.map(processor));
}
}
// Usage
awaitprocessInBatches(users,50,async(user)=>{
awaitsendEmail(user.email);
});

Q19: Security Best Practices - Production Grade

Answer:

Security breaches se company ka reputation kharab hota hai aur legal issues bhi aa sakte hain. Yeh practices follow karna zaroori hai.

1. Helmet.js - Security Headers:

const helmet =require('helmet');
app.use(helmet({
contentSecurityPolicy:{
directives:{
defaultSrc:["'self'"],
styleSrc:["'self'","'unsafe-inline'","https://cdn.example.com"],
scriptSrc:["'self'","https://trusted-cdn.com"],
imgSrc:["'self'","data:","https:"]
}
},
hsts:{
maxAge:31536000,// 1 year
includeSubDomains:true,
preload:true
},
frameguard:{action:'deny'},// Clickjacking prevention
noSniff:true,// Prevent MIME sniffing
xssFilter:true// XSS protection
}));

2. Input Validation:

const{ body, validationResult }=require('express-validator');
app.post('/api/register',
body('email').isEmail().normalizeEmail(),
body('password')
.isLength({min:8})
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/),
body('username')
.isLength({min:3,max:20})
.matches(/^[a-zA-Z0-9_]+$/),
async(req, res)=>{
const errors =validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()});
}
// Process registration
}
);

3. SQL Injection Prevention:

// ❌ VULNERABLE
const query =`SELECT * FROM users WHERE email = '${req.body.email}'`;
db.query(query);
// ✅ SAFE - Parameterized queries
const query ='SELECT * FROM users WHERE email = ?';
db.query(query,[req.body.email]);
// Mongoose automatically prevents injection
const user =await User.findOne({email: req.body.email });

4. NoSQL Injection Prevention:

const mongoSanitize =require('express-mongo-sanitize');
// Sanitize data
app.use(mongoSanitize({
replaceWith:'_',
onSanitize:({ req, key })=>{
    console.warn(`Sanitized ${key} in ${req.path}`);
}
}));
// Manual sanitization
functionsanitize(obj){
if(typeof obj ==='object'&& obj !==null){
for(const key in obj){
if(key.startsWith('$')){
delete obj[key];
}else{
sanitize(obj[key]);
}
}
}
return obj;
}

5. Rate Limiting:

const rateLimit =require('express-rate-limit');
// General API rate limit
const apiLimiter =rateLimit({
windowMs:15*60*1000,// 15 minutes
max:100,// 100 requests per window
message:'Too many requests from this IP',
standardHeaders:true,
legacyHeaders:false
});
app.use('/api/', apiLimiter);
// Stricter limit for authentication
const authLimiter =rateLimit({
windowMs:15*60*1000,
max:5,// 5 attempts
skipSuccessfulRequests:true,
message:'Too many login attempts'
});
app.post('/api/login', authLimiter, loginController);
// Dynamic rate limiting
const dynamicLimiter =rateLimit({
windowMs:60*1000,
max:(req)=>{
if(req.user && req.user.isPremium){
return1000;// Premium users
}
return100;// Free users
}
});

6. JWT Security:

const jwt =require('jsonwebtoken');
// Secure token generation
functiongenerateToken(user){
return jwt.sign(
{
id: user._id,
email: user.email,
role: user.role 

},
    process.env.JWT_SECRET,
{
expiresIn:'15m',// Short expiry
issuer:'myapp.com',
audience:'myapp-users'
}
);
}
// Refresh token
functiongenerateRefreshToken(user){
return jwt.sign(
{id: user._id },
    process.env.REFRESH_TOKEN_SECRET,
{expiresIn:'7d'}
);
}
// Secure verification
constverifyToken=(req, res, next)=>{
const token = req.headers['authorization']?.split(' ')[1];
if(!token){
return res.status(401).json({error:'No token provided'});
}
try{
const decoded = jwt.verify(token, process.env.JWT_SECRET,{
issuer:'myapp.com',
audience:'myapp-users'
});
    req.user = decoded;
next();
}catch(error){
if(error.name ==='TokenExpiredError'){
return res.status(401).json({error:'Token expired'});
}
return res.status(403).json({error:'Invalid token'});
}
};

7. HTTPS Only (Production):

// Force HTTPS redirect
app.use((req, res, next)=>{
if(process.env.NODE_ENV==='production'&&!req.secure){
return res.redirect(301,`https://${req.headers.host}${req.url}`);
}
next();
});
// Secure cookies
app.use(session({
secret: process.env.SESSION_SECRET,
resave:false,
saveUninitialized:false,
cookie:{
secure: process.env.NODE_ENV==='production',// HTTPS only
httpOnly:true,// Prevent XSS
maxAge:1000*60*60*24,// 1 day
sameSite:'strict'// CSRF protection
}
}));

Advanced level pe apne profile summary mein yeh mention karo: "Expert in Node.js architecture, scalability solutions, performance optimization, and security best practices. Led teams building high-traffic production systems."


Scenario-Based Interview Questions

Real-world problems jo production mein aate hain. Interviewer yeh scenarios deke aapki problem-solving skills test karta hai.

Scenario 1: API Slow Ho Raha Hai Production Mein - Kaise Debug Karoge?

Answer:

Yeh sabse common production issue hai. Step-by-step approach:

Step 1: Metrics Check Karo

// Add monitoring
const responseTime =require('response-time');
app.use(responseTime((req, res, time)=>{
  console.log(`${req.method} ${req.url} - ${time.toFixed(2)}ms`);
// Alert if too slow
if(time >1000){
    logger.warn(`Slow API: ${req.url} took ${time}ms`);
}
}));

Step 2: Database Queries Profile Karo

// Mongoose query logging
mongoose.set('debug',true);
// Check slow queries
const query = User.find({status:'active'})
.explain('executionStats');
// Results show:
// - executionTimeMillis
// - totalDocsExamined
// - If index was used
// Solution: Add index
userSchema.index({status:1,createdAt:-1});

Step 3: N+1 Query Problem Check Karo

// ❌ N+1 Problem - Database ke 101 queries
asyncfunctiongetUsers(){
const users =await User.find();// 1 query
for(const user of users){
    user.orders =await Order.find({userId: user._id });// N queries
}
return users;
}
// ✅ Solution - Single query with populate
asyncfunctiongetUsers(){
const users =await User.find()
.populate('orders')// Single join
.lean();
return users;
}

Step 4: Caching Implement Karo

const redis =require('redis');
const client = redis.createClient();
asyncfunctiongetProducts(category){
const cacheKey =`products:${category}`;
// Check cache first
const cached =await client.get(cacheKey);
if(cached){
returnJSON.parse(cached);
}
// Cache miss - fetch from DB
const products =await Product.find({ category }).lean();
// Store in cache for 5 minutes
await client.setex(cacheKey,300,JSON.stringify(products));
return products;
}

Step 5: External API Calls Optimize Karo

// ❌ Sequential - 3 seconds
asyncfunctiongetUserData(userId){
const profile =awaitfetchProfile(userId);// 1s
const orders =awaitfetchOrders(userId);// 1s
const reviews =awaitfetchReviews(userId);// 1s
return{ profile, orders, reviews };
}
// ✅ Parallel - 1 second
asyncfunctiongetUserData(userId){
const[profile, orders, reviews]=await Promise.all([
fetchProfile(userId),
fetchOrders(userId),
fetchReviews(userId)
]);
return{ profile, orders, reviews };
}

Scenario 2: High Traffic Mein Server Crash Ho Raha Hai

Answer:

Black Friday ya promotional events mein traffic spike se yeh problem aati hai.

Step 1: Load Balancing Setup Karo

// PM2 cluster mode
// ecosystem.config.js
module.exports ={
apps:[{
name:'api-server',
script:'./server.js',
instances:'max',// CPU cores ke barabar
exec_mode:'cluster',
max_memory_restart:'500M',
env:{
NODE_ENV:'production',
PORT:3000
}
}]
};
// Start with PM2
// pm2 start ecosystem.config.js

Step 2: Rate Limiting Add Karo

const rateLimit =require('express-rate-limit');
const limiter =rateLimit({
windowMs:1*60*1000,// 1 minute
max:60,// 60 requests per minute per IP
message:{
error:'Too many requests, please try again later'
},
standardHeaders:true,
legacyHeaders:false,
// Skip for trusted IPs
skip:(req)=>{
return trustedIPs.includes(req.ip);
}
});
app.use('/api/', limiter);

Step 3: Database Connection Pool Increase Karo

mongoose.connect(process.env.DB_URI,{
poolSize:50,// Default 10 se increase karo
socketTimeoutMS:45000,
keepAlive:true,
keepAliveInitialDelay:300000
});

Step 4: Queue System Implement Karo

const Queue =require('bull');
const sendEmailQueue =newQueue('sendEmail', process.env.REDIS_URL);
// Add to queue instead of processing immediately
app.post('/api/register',async(req, res)=>{
const user =await User.create(req.body);
// Don't send email synchronously
await sendEmailQueue.add({
email: user.email,
name: user.name 

});
  res.status(201).json({ user,message:'Registration successful'});
});
// Worker process (separate file/server)
sendEmailQueue.process(async(job)=>{
awaitsendWelcomeEmail(job.data.email, job.data.name);
});

Step 5: CDN Use Karo Static Assets Ke Liye

// Static files ko CDN se serve karo
// CloudFlare, AWS CloudFront, Azure CDN
// In code
constCDN_URL= process.env.CDN_URL||'';
res.json({
user:{
name:'John',
avatar:`${CDN_URL}/images/avatars/${user.id}.jpg`
}
});

Scenario 3: Memory Usage Continuously Badh Raha Hai

Answer:

Memory leak detect karna aur fix karna critical hai.

Step 1: Memory Monitoring

// Monitor memory usage
setInterval(()=>{
const usage = process.memoryUsage();
  console.log({
rss:`${(usage.rss / 1024 / 1024).toFixed(2)} MB`,
heapUsed:`${(usage.heapUsed / 1024 / 1024).toFixed(2)} MB`,
heapTotal:`${(usage.heapTotal / 1024 / 1024).toFixed(2)} MB`,
external:`${(usage.external / 1024 / 1024).toFixed(2)} MB`
});
},10000);
// Alert if memory crosses threshold
constMAX_MEMORY_MB=400;
if(usage.heapUsed /1024/1024>MAX_MEMORY_MB){
  logger.error('High memory usage detected!');
// Send alert to Slack/PagerDuty
}

Step 2: Common Memory Leak Fix Karo

// ❌ LEAK: Event listeners not removed
classUserService{
constructor(){
this.eventEmitter =newEventEmitter();
// Har instance pe listener add ho raha hai
this.eventEmitter.on('userCreated',this.handleUser);
}
handleUser(user){
    console.log('User created:', user);
}
}
// ✅ FIX: Remove listeners
classUserService{
constructor(){
this.eventEmitter =newEventEmitter();
this.handleUser =this.handleUser.bind(this);
this.eventEmitter.on('userCreated',this.handleUser);
}
cleanup(){
this.eventEmitter.removeListener('userCreated',this.handleUser);
}
}
// ❌ LEAK: Global cache without limit
const cache ={};
functioncacheData(key, value){
  cache[key]= value;// Infinitely grows
}
// ✅ FIX: Use LRU cache
constLRU=require('lru-cache');
const cache =newLRU({
max:500,// Maximum 500 items
maxAge:1000*60*60,// 1 hour TTL
updateAgeOnGet:true
});
functioncacheData(key, value){
  cache.set(key, value);
}

Step 3: Heap Snapshot Analyze Karo

# Take heap snapshot
node --inspect app.js

# In Chrome DevTools (chrome://inspect)
# Take heap snapshot
# Compare snapshots to find leaks
# Or use heapdump module
npminstall heapdump
const heapdump =require('heapdump');
// Manually take snapshot
app.get('/heapdump',(req, res)=>{
const filename =`/tmp/heapdump-${Date.now()}.heapsnapshot`;
  heapdump.writeSnapshot(filename,(err)=>{
if(err){
return res.status(500).json({error: err.message });
}
    res.json({file: filename });
});
});

Scenario-based questions ke liye situational interview questions guide bhi padho for better understanding of problem-solving approaches.


Node JS Coding Interview Questions

Real node js coding interview questions with complete implementations. Interviewer yeh live coding rounds mein puchta hai.

Coding Q1: Simple REST API with CRUD Operations

const express =require('express');
const app =express();
app.use(express.json());
// In-memory database
let products =[
{id:1,name:'Laptop',price:50000,category:'Electronics'},
{id:2,name:'Phone',price:20000,category:'Electronics'},
{id:3,name:'Shirt',price:500,category:'Clothing'}
];
// GET all products
app.get('/api/products',(req, res)=>{
const{ category, minPrice, maxPrice }= req.query;
let filtered = products;
// Filter by category
if(category){
    filtered = filtered.filter(p=> p.category === category);
}
// Filter by price range
if(minPrice){
    filtered = filtered.filter(p=> p.price >=parseInt(minPrice));
}
if(maxPrice){
    filtered = filtered.filter(p=> p.price <=parseInt(maxPrice));
}
  res.json({
success:true,
count: filtered.length,
products: filtered

});
});
// GET single product
app.get('/api/products/:id',(req, res)=>{
const product = products.find(p=> p.id ===parseInt(req.params.id));
if(!product){
return res.status(404).json({
success:false,
error:'Product not found'
});
}
  res.json({success:true, product });
});
// POST new product
app.post('/api/products',(req, res)=>{
const{ name, price, category }= req.body;
// Validation
if(!name ||!price ||!category){
return res.status(400).json({
success:false,
error:'Please provide name, price, and category'
});
}
if(price <=0){
return res.status(400).json({
success:false,
error:'Price must be positive'
});
}
const newProduct ={
id: products.length +1,
    name,
    price,
    category

};
  products.push(newProduct);
  res.status(201).json({
success:true,
product: newProduct

});
});
// PUT update product
app.put('/api/products/:id',(req, res)=>{
const product = products.find(p=> p.id ===parseInt(req.params.id));
if(!product){
return res.status(404).json({
success:false,
error:'Product not found'
});
}
const{ name, price, category }= req.body;
if(name) product.name = name;
if(price){
if(price <=0){
return res.status(400).json({
success:false,
error:'Price must be positive'
});
}
    product.price = price;
}
if(category) product.category = category;
  res.json({success:true, product });
});
// DELETE product
app.delete('/api/products/:id',(req, res)=>{
const index = products.findIndex(p=> p.id ===parseInt(req.params.id));
if(index ===-1){
return res.status(404).json({
success:false,
error:'Product not found'
});
}
  products.splice(index,1);
  res.json({
success:true,
message:'Product deleted successfully'
});
});
// Error handling middleware
app.use((err, req, res, next)=>{
  console.error(err.stack);
  res.status(500).json({
success:false,
error:'Server error'
});
});
app.listen(3000,()=>{
  console.log('Server running on port 3000');
});

Coding Q2: Authentication Middleware with JWT

const express =require('express');
const jwt =require('jsonwebtoken');
const bcrypt =require('bcrypt');
const app =express();
app.use(express.json());
constJWT_SECRET='your-secret-key-change-in-production';
// Mock user database
const users =[];
// Register endpoint
app.post('/api/auth/register',async(req, res)=>{
try{
const{ username, email, password }= req.body;
// Validation
if(!username ||!email ||!password){
return res.status(400).json({
success:false,
error:'Please provide username, email, and password'
});
}
if(password.length <6){
return res.status(400).json({
success:false,
error:'Password must be at least 6 characters'
});
}
// Check if user already exists
const existingUser = users.find(u=> u.email === email);
if(existingUser){
return res.status(400).json({
success:false,
error:'User already exists'
});
}
// Hash password
const salt =await bcrypt.genSalt(10);
const hashedPassword =await bcrypt.hash(password, salt);
// Create user
const user ={
id: users.length +1,
      username,
      email,
password: hashedPassword,
createdAt:newDate()
};
    users.push(user);
// Generate token
const token = jwt.sign(
{id: user.id,email: user.email },
JWT_SECRET,
{expiresIn:'7d'}
);
    res.status(201).json({
success:true,
      token,
user:{
id: user.id,
username: user.username,
email: user.email

}
});
}catch(error){
    res.status(500).json({
success:false,
error: error.message

});
}
});
// Login endpoint
app.post('/api/auth/login',async(req, res)=>{
try{
const{ email, password }= req.body;
// Validation
if(!email ||!password){
return res.status(400).json({
success:false,
error:'Please provide email and password'
});
}
// Find user
const user = users.find(u=> u.email === email);
if(!user){
return res.status(401).json({
success:false,
error:'Invalid credentials'
});
}
// Check password
const isMatch =await bcrypt.compare(password, user.password);
if(!isMatch){
return res.status(401).json({
success:false,
error:'Invalid credentials'
});
}
// Generate token
const token = jwt.sign(
{id: user.id,email: user.email },
JWT_SECRET,
{expiresIn:'7d'}
);
    res.json({
success:true,
      token,
user:{
id: user.id,
username: user.username,
email: user.email

}
});
}catch(error){
    res.status(500).json({
success:false,
error: error.message

});
}
});
// Authentication middleware
constauth=(req, res, next)=>{
try{
// Get token from header
const authHeader = req.headers.authorization;
if(!authHeader ||!authHeader.startsWith('Bearer ')){
return res.status(401).json({
success:false,
error:'No token provided'
});
}
const token = authHeader.split(' ')[1];
// Verify token
const decoded = jwt.verify(token,JWT_SECRET);
// Attach user to request
    req.user = decoded;
next();
}catch(error){
if(error.name ==='TokenExpiredError'){
return res.status(401).json({
success:false,
error:'Token expired'
});
}
return res.status(403).json({
success:false,
error:'Invalid token'
});
}
};
// Protected route
app.get('/api/profile', auth,(req, res)=>{
const user = users.find(u=> u.id === req.user.id);
if(!user){
return res.status(404).json({
success:false,
error:'User not found'
});
}
  res.json({
success:true,
user:{
id: user.id,
username: user.username,
email: user.email,
createdAt: user.createdAt

}
});
});
// Update profile (protected)
app.put('/api/profile', auth,async(req, res)=>{
try{
const user = users.find(u=> u.id === req.user.id);
if(!user){
return res.status(404).json({
success:false,
error:'User not found'
});
}
const{ username, password }= req.body;
if(username){
      user.username = username;
}
if(password){
if(password.length <6){
return res.status(400).json({
success:false,
error:'Password must be at least 6 characters'
});
}
const salt =await bcrypt.genSalt(10);
      user.password =await bcrypt.hash(password, salt);
}
    res.json({
success:true,
user:{
id: user.id,
username: user.username,
email: user.email

}
});
}catch(error){
    res.status(500).json({
success:false,
error: error.message

});
}
});
app.listen(3000,()=>{
  console.log('Server running on port 3000');
});

Coding Q3: Pagination API

const express =require('express');
const app =express();
app.use(express.json());
// Mock data - 100 users
const users = Array.from({length:100},(_, i)=>({
id: i +1,
name:`User ${i + 1}`,
email:`user${i + 1}@example.com`,
age: Math.floor(Math.random()*50)+18,
city:['Mumbai','Delhi','Bangalore','Pune'][Math.floor(Math.random()*4)]
}));
// Pagination middleware
constpaginate=(model)=>{
return(req, res, next)=>{
const page =parseInt(req.query.page)||1;
const limit =parseInt(req.query.limit)||10;
const sort = req.query.sort ||'id';
const order = req.query.order ==='desc'?-1:1;
// Calculate start and end index
const startIndex =(page -1)* limit;
const endIndex = page * limit;
const results ={};
// Total count
    results.total = model.length;
// Pagination info
    results.page = page;
    results.limit = limit;
    results.totalPages = Math.ceil(model.length / limit);
// Previous page
if(startIndex >0){
      results.previous ={
page: page -1,
limit: limit

};
}
// Next page
if(endIndex < model.length){
      results.next ={
page: page +1,
limit: limit

};
}
// Slice data
let data =[...model];
// Sort data
    data.sort((a, b)=>{
if(a[sort]< b[sort])return-1* order;
if(a[sort]> b[sort])return1* order;
return0;
});
    results.data = data.slice(startIndex, endIndex);
    res.paginatedResults = results;
next();
};
};
// GET users with pagination
app.get('/api/users',paginate(users),(req, res)=>{
  res.json({
success:true,
...res.paginatedResults

});
});
// Advanced pagination with filters
app.get('/api/users/search',(req, res)=>{
const page =parseInt(req.query.page)||1;
const limit =parseInt(req.query.limit)||10;
const city = req.query.city;
const minAge =parseInt(req.query.minAge)||0;
const maxAge =parseInt(req.query.maxAge)||100;
// Filter data
let filtered = users.filter(user=>{
return user.age >= minAge && user.age <= maxAge;
});
if(city){
    filtered = filtered.filter(user=> user.city === city);
}
// Calculate pagination
const startIndex =(page -1)* limit;
const endIndex = page * limit;
const results ={
success:true,
total: filtered.length,
page: page,
limit: limit,
totalPages: Math.ceil(filtered.length / limit),
data: filtered.slice(startIndex, endIndex)
};
if(startIndex >0){
    results.previous ={page: page -1,limit: limit };
}
if(endIndex < filtered.length){
    results.next ={page: page +1,limit: limit };
}
  res.json(results);
});
// Cursor-based pagination (for real-time data)
app.get('/api/users/cursor',(req, res)=>{
const cursor =parseInt(req.query.cursor)||0;
const limit =parseInt(req.query.limit)||10;
// Find data after cursor
const data = users

.filter(user=> user.id > cursor)
.slice(0, limit);
const nextCursor = data.length >0? data[data.length -1].id :null;
  res.json({
success:true,
data: data,
nextCursor: nextCursor,
hasMore: data.length === limit

});
});
app.listen(3000,()=>{
  console.log('Server running on port 3000');
});

Coding Q4: File Upload with Multer

const express =require('express');
const multer =require('multer');
const path =require('path');
const fs =require('fs');
const app =express();
// Create uploads directory if not exists
const uploadDir ='./uploads';
if(!fs.existsSync(uploadDir)){
  fs.mkdirSync(uploadDir);
}
// Configure storage
const storage = multer.diskStorage({
destination:function(req, file, cb){
cb(null, uploadDir);
},
filename:function(req, file, cb){
// Unique filename: timestamp-originalname
const uniqueSuffix = Date.now()+'-'+ Math.round(Math.random()*1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
}
});
// File filter
constfileFilter=(req, file, cb)=>{
// Allowed extensions
const allowedTypes =/jpeg|jpg|png|gif|pdf|doc|docx/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = allowedTypes.test(file.mimetype);
if(extname && mimetype){
returncb(null,true);
}else{
cb(newError('Invalid file type. Only JPEG, PNG, GIF, PDF, DOC, DOCX are allowed.'));
}
};
// Configure multer
const upload =multer({
storage: storage,
limits:{
fileSize:5*1024*1024// 5MB max file size
},
fileFilter: fileFilter

});
// Single file upload
app.post('/api/upload/single', upload.single('file'),(req, res)=>{
if(!req.file){
return res.status(400).json({
success:false,
error:'Please upload a file'
});
}
  res.json({
success:true,
message:'File uploaded successfully',
file:{
filename: req.file.filename,
originalname: req.file.originalname,
mimetype: req.file.mimetype,
size: req.file.size,
path: req.file.path

}
});
});
// Multiple files upload
app.post('/api/upload/multiple', upload.array('files',5),(req, res)=>{
if(!req.files || req.files.length ===0){
return res.status(400).json({
success:false,
error:'Please upload at least one file'
});
}
const files = req.files.map(file=>({
filename: file.filename,
originalname: file.originalname,
mimetype: file.mimetype,
size: file.size,
path: file.path

}));
  res.json({
success:true,
message:`${files.length} files uploaded successfully`,
files: files

});
});
// Multiple fields upload
app.post('/api/upload/fields',
  upload.fields([
{name:'avatar',maxCount:1},
{name:'documents',maxCount:3}
]),
(req, res)=>{
if(!req.files){
return res.status(400).json({
success:false,
error:'Please upload files'
});
}
const result ={
success:true,
message:'Files uploaded successfully'
};
if(req.files.avatar){
      result.avatar = req.files.avatar[0];
}
if(req.files.documents){
      result.documents = req.files.documents;
}
    res.json(result);
}
);
// Image upload with validation
app.post('/api/upload/image', upload.single('image'),(req, res)=>{
if(!req.file){
return res.status(400).json({
success:false,
error:'Please upload an image'
});
}
// Additional image validation (you can use sharp library for this)
const allowedMimetypes =['image/jpeg','image/png','image/gif'];
if(!allowedMimetypes.includes(req.file.mimetype)){
// Delete uploaded file
    fs.unlinkSync(req.file.path);
return res.status(400).json({
success:false,
error:'Only image files (JPEG, PNG, GIF) are allowed'
});
}
  res.json({
success:true,
message:'Image uploaded successfully',
image:{
filename: req.file.filename,
url:`/uploads/${req.file.filename}`,
size: req.file.size

}
});
});
// Serve uploaded files
app.use('/uploads', express.static(uploadDir));
// Delete file endpoint
app.delete('/api/files/:filename',(req, res)=>{
const filename = req.params.filename;
const filepath = path.join(uploadDir, filename);
// Check if file exists
if(!fs.existsSync(filepath)){
return res.status(404).json({
success:false,
error:'File not found'
});
}
// Delete file
  fs.unlinkSync(filepath);
  res.json({
success:true,
message:'File deleted successfully'
});
});
// Error handling for multer
app.use((err, req, res, next)=>{
if(err instanceofmulter.MulterError){
if(err.code ==='LIMIT_FILE_SIZE'){
return res.status(400).json({
success:false,
error:'File size too large. Maximum 5MB allowed.'
});
}
if(err.code ==='LIMIT_UNEXPECTED_FILE'){
return res.status(400).json({
success:false,
error:'Unexpected file field'
});
}
}
  res.status(500).json({
success:false,
error: err.message

});
});
app.listen(3000,()=>{
  console.log('Server running on port 3000');
});

In coding examples ko apne GitHub profile pe upload karo aur resume mein link do. Interviewers ko live projects dekhne pasand aate hain.


Common Mistakes Candidates Make in Node.js Interviews

Real interviews mein yeh mistakes sabse zyada hoti hain. In mistakes se bachna zaroori hai.

Mistake 1: Synchronous Functions Ka Galat Use

Wrong:

javascriptconst fs =require('fs');
app.get('/api/data',(req, res)=>{const data = fs.readFileSync('large-file.json');
// BLOCKS event loop

res.json(JSON.parse(data));
});

Why Wrong: Server ko 10,000 requests aaye toh ek ek karke process honge. Server hang ho jayega.

Correct:

javascriptconst fs =require('fs').promises;
app.get('/api/data',async(req, res)=>{try{const data =await fs.readFile('large-file.json','utf8');
res.json(JSON.parse(data));
}catch(error){
res.status(500).json({error: error.message });
}});

Mistake 2: Error Handling Ignore Karna

Wrong:

javascriptasyncfunctiongetUser(id){const user =await User.findById(id);// Agar error aaye?return user;
}

Why Wrong: Production mein database down ho, network fail ho - app crash kar jayega.

Correct:

javascriptasyncfunctiongetUser(id){try{const user =await User.findById(id);
if(!user){thrownewError('User not found');
}return user;}catch(error){
console.error('Failed to fetch user:', error);
throw error;// Re-throw for upstream handling
}}

Mistake 3: Callback Hell Banana

Wrong:

getUser(userId, (err, user) => {
  if (err) throw err;

  getOrders(user.id, (err, orders) => {
    if (err) throw err;

    getOrderDetails(orders[0].id, (err, details) => {
      if (err) throw err;
      // More nesting...
    });
  });
});

Why Wrong: Code unreadable aur maintain karna mushkil hai.

Correct:

async function getUserData(userId) {
  try {
    const user = await getUser(userId);
    const orders = await getOrders(user.id);
    const details = await getOrderDetails(orders[0].id);

    return { user, orders, details };
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

Mistake 4: Environment Variables Hardcode Karna

Wrong:

mongoose.connect('mongodb://admin:password123@localhost/mydb');
const JWT_SECRET = 'mysecretkey123';

Why Wrong: Security risk! Code GitHub pe push kiya toh credentials leak ho jayenge.

Correct:

require('dotenv').config();

mongoose.connect(process.env.DB_URI);
const JWT_SECRET = process.env.JWT_SECRET;

Mistake 5: N+1 Query Problem

Wrong:

async function getUsersWithPosts() {
  const users = await User.find(); // 1 query

  for (const user of users) {
    user.posts = await Post.find({ userId: user.id }); // N queries
  }

  return users;
}

// Total: 1 + N queries (if 100 users = 101 queries)

Why Wrong: Database pe bahut load, response time slow.

Correct:

async function getUsersWithPosts() {
  const users = await User.find()
    .populate('posts')
    .lean();

  return users;
}

// Total: 1 query only


Mistake 6: Infinite Loops with process.nextTick()

Wrong:

javascriptfunctioninfiniteLoop(){  
process.nextTick(infiniteLoop);// DANGER!
}infiniteLoop();

Why Wrong: Event loop block ho jayega, server freeze kar jayega.

Correct:

javascriptfunctionscheduledTask(){setImmediate(()=>{// Do work// This allows other operations to run
});
}

Mistake 7: Not Handling Promise Rejections

Wrong:

javascriptfetch('/api/data').then(res=> res.json()).then(data=> console.log(data));// No .catch()!

Why Wrong: Unhandled promise rejection se app crash ho sakta hai (Node 15+).

Correct:

javascriptfetch('/api/data').then(res=> res.json()).then(data=> 
console.log(data))
.catch(error=> console.error('Error:', error));// Or with async/await
try{const res =awaitfetch('/api/data');
const data =await res.json();
console.log(data);
}catch(error){
console.error('Error:', error);
}

Mistake 8: Not Using Connection Pooling

Wrong:

javascriptasyncfunctionqueryDatabase(){
const connection =awaitcreateConnection(DB_URI);
const result =await connection.query('SELECT * FROM users');
await connection.close();
return result;
}// Har request pe new connection!

Why Wrong: Connection overhead bahut zyada hai, slow performance.

Correct:

javascript// Setup oncemongoose.connect(DB_URI,{poolSize:10// Connection pool});
// Reuse connectionsasyncfunctionqueryDatabase(){const result =await User.find();
return result;
}

Interview preparation ke liye common interview mistakes guide bhi padho to avoid basic errors.


Node JS Interview Preparation Tips (Indian Job Market)

Indian IT market specific tips jo interview crack karne mein madad karenge.

Resume Tips

1. Resume Mein Node.js Skills Properly Highlight Karo:

textTechnical Skills:
- Backend: Node.js, Express.js, NestJS
- Databases: MongoDB, PostgreSQL, Redis
- Authentication: JWT, OAuth 2.0, Passport.js
- Tools: PM2, Docker, Git, Postman
- Testing: Jest, Mocha, Supertest
- Cloud: AWS (EC2, S3, Lambda), Azure

Tech resume format follow karo specifically Indian companies ke liye. ATS-friendly format use karo taaki automated screening systems tumhara resume select karein.

2. Projects Section Mein Live Links Do:

textProjects:
• E-Commerce API | Node.js, Express, MongoDB
  - Built RESTful API handling 10,000+ daily requests
  - Implemented JWT authentication & role-based access
  - Deployed on AWS EC2 with PM2 clustering
  - GitHub: github.com/username/ecommerce-api
  - Live: api.myproject.com

3. Quantify Your Achievements:

  • "Improved API response time by 60% using Redis caching"

  • "Handled 50,000+ concurrent users during peak traffic"

  • "Reduced database queries by 40% through optimization"

Check resume achievements guide for more examples.

GitHub Profile Setup

1. Active Profile Dikhao:

  • Minimum 5-6 Node.js projects banao and inhe profile se attached karo

  • README files properly likho jisse aapke project ke bare mai interviewer ko kuch samajh mai aaye

  • Code comments achhe se likho isse pata lagta h ki code of line kis bare mai h

  • Contribution graph green rakho

2. Sample Projects:

  • REST API with authentication

  • Real-time chat application (Socket.io)

  • Microservices architecture

  • API with caching & rate limiting

Project documentation properly karo GitHub pe.

How to Explain Projects in Interview

STAR Method Use Karo:

Situation: Problem kya tha?
Task: Tumhara kya role tha?
Action: Kya kiya specifically?
Result: Outcome kya tha? (numbers ke saath)

Example:

"Sir, maine ek e-commerce backend API banaya tha. Situation: Company ko scalable backend chahiye tha jo peak times mein 10,000 concurrent users handle kar sake. Task: Mujhe API design karna tha with authentication, payment integration, aur order management. Action: Maine Node.js Express use kiya, MongoDB database, JWT authentication implement kiya, Redis caching add kiya for product listings, aur PM2 clustering use kiya. Result: API 99.9% uptime achieve kiya, response time 200ms se neeche raha, aur successfully Black Friday traffic handle kiya without any crash."

What Interviewers Actually Check

1. Conceptual Clarity:

  • Event loop samajhte ho ya nahi

  • Async programming ka practical knowledge

  • Database interaction patterns

2. Production Experience:

  • Error handling karte ho ya nahi

  • Logging implement karte ho?

  • Environment variables use karte ho?

3. Problem-Solving Ability:

  • Live coding rounds mein approach

  • Edge cases sochte ho ya nahi

  • Code cleanup aur optimization

4. Communication Skills:

  • Technical concepts ko simple language mein explain kar sakte ho?

  • Questions clearly poochte ho?

  • Hindi-English mix comfortable ho (most Indian companies)

Company-Specific Tips

Startups (Swiggy, Zomato, CRED):

  • Ownership aur initiative dikhao

  • End-to-end features build karne ka experience

  • Fast-paced environment mein kaam kar sakte ho?

Service Companies (TCS, Infosys, Wipro):

  • Team collaboration skills

  • Documentation aur process following

  • Client communication abilities

Product Companies (Flipkart, Amazon, PayPal):

  • Scale aur performance focus

  • System design knowledge

  • Code quality aur best practices

MNCs (Microsoft, Google):

Preparation Timeline

2-3 Weeks Before Interview:

  • Node.js core concepts revise karo

  • 10-15 coding problems practice karo

  • 2-3 projects GitHub pe deploy karo

1 Week Before:

  • Company research karo

  • Previous interview experiences padho (Glassdoor, AmbitionBox)

  • Mock interviews karo

1 Day Before:

Interview tips ke liye yeh guides bhi helpful hain:

Conclusion

Node.js interviews India mein competitive hain, but proper preparation se aap easily crack kar sakte ho. Is comprehensive guide mein humnenode js interview questions- freshers se lekar advanced level tak - sab cover kiye hain real code examples aur production scenarios ke saath.

Key Takeaways:

  1. Core Concepts Master Karo: Event loop, asynchronous programming, streams - yeh foundation hain

  2. Hands-on Practice Zaroori Hai: 3-4 projects GitHub pe deploy karo with proper documentation

  3. Production Knowledge Dikhao: Error handling, security, performance optimization - yeh differentiate karega tumhe

  4. Real-world Scenarios Prepare Karo: API slow ho, memory leak ho, high traffic - in situations ko handle karna aana chahiye

  5. Communication Skills: Technical concepts ko simple Hinglish mein explain kar sako

Resume Preparation:

Interview ke saath-saath apna resume bhi top-notch rakho:

Next Steps:

  1. Is article ke questions ko category-wise practice karo

  2. Har week 5-10 coding problems solve karo

  3. LinkedIn aur GitHub profile active rakho

  4. Mock interviews schedule karo friends/mentors ke saath

  5. Company research karo before applying

Additional Resources:

Related interview guides jo helpful hain:

Final Words:

Remember, interview ek conversation hai, exam nahi. Interviewers dekhna chahte hain ki aap problems ko logically solve kar sakte ho, team mein fit honge, aur continuously seekhne ki willingness hai. Confidence rakho, honest raho, aur agar kuch nahi aata toh admit karo - "I haven't worked with this yet, but I can learn quickly."

All the best for your Node.js interview! ?

Agar aur questions hain ya specific topics pe detail chahiye, toh comment karo. Indian developers ke liye yeh guide continuously update karte rahenge latest trends aur interview patterns ke basis pe.

Job Search Resources:

Happy Coding & Good Luck! ?✨

Frequently Asked Questions

Q1: Node.js interview mein sabse zyada kya puchha jaata hai?

Node.js interviews mein teen main areas par focus hota hai: Core concepts jaise event loop, asynchronous programming, callbacks, promises aur async/await. Practical implementation jaise REST APIs, authentication, database integration aur error handling. Production knowledge jaise performance optimization, security, scaling aur deployment. Freshers ke liye basics important hote hain, experienced developers ke liye architecture aur scalability zyada important hota hai.

Q2: Fresher ke liye Node.js interview kitna tough hota hai?

Fresher interviews mostly basic concepts par focus karte hain: Node.js kya hai aur kaise kaam karta hai, event loop ki basic understanding, callback vs promise vs async/await, simple REST API banana, npm aur package.json ka use, aur basic error handling. Difficulty level medium hota hai. Agar 2-3 projects banaye hain aur concepts clear hain to interview crack kar sakte ho. Preparation ke liye 5-6 core concepts thoroughly samjho, 2-3 small projects GitHub par rakho, aur basic coding practice karo.

Q3: Node.js vs Express.js mein kya difference hai?

Node.js ek JavaScript runtime environment hai jo server side JavaScript run karta hai aur core platform ka kaam karta hai. Express.js Node.js ke upar built web framework hai jo routing, middleware aur HTTP utilities provide karta hai aur web development ko fast aur simple banata hai. Simple samjho to Node.js platform hai aur Express.js us platform par built framework hai.

Q4: Node.js interview ke liye kitne din ki preparation chahiye?

Preparation time experience level par depend karta hai. Freshers ke liye 2-3 weeks minimum chahiye jisme concepts clear karo, 3-4 projects banao aur 20-30 interview questions practice karo. 1-3 saal experience walon ke liye 1-2 weeks focused preparation kaafi hoti hai jisme production experience revise aur advanced topics padhe jaate hain. 3+ years walon ke liye 1 week refresher enough hota hai jisme architecture aur scenario based questions revise kiye jaate hain.

Q5: Salary negotiations mein Node.js developers ko kya expect karna chahiye India mein?

Salary experience, city aur company type par depend karti hai. Freshers ke liye roughly 3-8 LPA, 1-3 years ke liye 6-15 LPA, 3-5 years ke liye 12-25 LPA, aur 5+ years ke liye 20-50 LPA ya usse zyada ho sakta hai. Salary par company type, skillset jaise cloud ya microservices, projects portfolio aur previous CTC ka strong impact hota hai. Negotiation ke liye market salary research karo, 30-50 percent hike realistic hota hai, aur unique skills highlight karo.

Why Trust Resumeera for Node JS Interview Questions 2026: Complete Guide for Indian Developers (Freshers to Advanced)?

Why Trust Resumeera for Node JS Interview Questions 2026: Complete Guide for Indian Developers (Freshers to Advanced)?

Sharukh Khan – Certified Resume Expert

written by (Sharukh Khan + AI)
Co-Founder & Career Expert

The insights shared here are based on real ATS screening experience, resume shortlisting patterns, and hands-on work with job seekers.

Last reviewed & updated: February 2026 | Published on Resumeera.xyz

Related Articles

बीमा क्या है? जीवन बीमा और सामान्य बीमा की पूरी जानकारी | ResumeEra
बीमा क्या है? जीवन बीमा और सामान्य बीमा की पूरी जानकारी | ResumeEra
Read →
Free Resume Builder — No Hidden Fee, No Any Charges, Only 2 Minutes to Create Resume
Free Resume Builder — No Hidden Fee, No Any Charges, Only 2 Minutes to Create Resume
Read →
2026 की सर्वश्रेष्ठ Resume Writing Services – पूरी जानकारी हिंदी में
2026 की सर्वश्रेष्ठ Resume Writing Services – पूरी जानकारी हिंदी में
Read →
AI Se Banaya Resume Aapki Naukri Chhin Sakta Hai — 67% Managers Ne Khud Bataya
AI Se Banaya Resume Aapki Naukri Chhin Sakta Hai — 67% Managers Ne Khud Bataya
Read →