node js interview questions for freshers

Node.js Interview Questions Freshers Ke Liye — Event Loop Se REST API Tak

25 July 202612 min read

Node.js Interview Questions Freshers Ke Liye — Pehle Yeh Samajh Le

Bhai scene aksar yeh hota hai — MERN seekh liya, ek CRUD API bana li, resume pe "Node.js, Express, MongoDB" likh diya. Phir interview me pehla sawaal aata hai "Node single-threaded hai to hazaaron requests kaise handle karta hai?" — aur tum "event loop hota hai na" bolke ruk jaate ho. Interviewer ki agli line hoti hai "achha, event loop ke phases bata do" — aur wahi pe game khatam.

Problem knowledge ki nahi hai. Problem yeh hai ki backend ke answers layered hote hain — har answer ke peeche ek follow-up khada hota hai. Yeh blog exactly wahi layers khol raha hai. Neeche node js interview questions for freshers ke saat cluster hain, har cluster me wahi sawaal jo Indian service-based companies (TCS, Infosys, Wipro, Cognizant) aur chhote product startups dono me sach me poochhe jaate hain — chhote model answers ke saath, jitna interview me actually bolna hota hai.

Depth aur poora question bank chahiye to Node chapter par jao — wahan notes, practice questions aur code walkthrough sab hai. Yahan focus hai strategy aur bolne wale answers par.

Ek hi rule: har answer bol ke practice karo. Mann me padha hua answer interview me nahi nikalta.

Cluster 1 — Node Kya Hai + "Single-Threaded" Wala Trap

Yeh warm-up hai, par yahi pe sabse zyada log adhoora answer dete hain.

Q. Node.js kya hai — language, framework, ya runtime? Runtime. Node ek JavaScript runtime hai jo Google ke V8 engine par bana hai, plus libuv naam ki C library. Iski wajah se JavaScript browser ke bahar — server par — chal paati hai. JavaScript language hai, Express framework hai, Node runtime hai.

Q. Node single-threaded hai to hazaaron concurrent requests kaise handle karta hai? Yeh sabse zyada poocha jaane wala sawaal hai, aur yahan aadha answer dena sabse aasan hai. Sahi answer:

Meri JavaScript ek hi thread par chalti hai, par wait us thread par hota hi nahi. Network I/O — HTTP, DB connections, sockets — OS kernel me hi non-blocking hai (Linux par epoll, macOS par kqueue, Windows par IOCP). Node saari sockets kernel ke paas register kar deta hai aur event loop ke poll phase me poochta hai "kaun ready hai". Isme koi extra thread lagta hi nahi. Sirf fs, dns.lookup, zlib aur CPU-heavy crypto libuv ke worker pool (default 4 threads) par jaate hain, kyunki inke liye koi sacchi non-blocking kernel API hoti hi nahi.

Yeh answer isliye strong hai kyunki bahut se freshers bolte hain "sab kuch thread pool par jaata hai" — jo galat hai. Socho: 500 waiting sockets 4 threads me fit ho hi nahi sakti. Agar sab kuch pool par jaata to Node ka poora point khatam ho jaata.

Q. Node kis kaam me weak hai? CPU-heavy kaam me. Image resize, bada loop, hashing — yeh sab pure JS computation hai, I/O nahi, isliye kernel ya worker pool madad nahi kar sakta. Us waqt tumhara ek JS thread busy hai aur baaki requests atak jaati hain. Yahi classic "don't block the event loop" problem hai. Iska hal worker_threads hai (ya us kaam ke liye koi doosra tool).

Q. Node MERN me kahan fit hota hai? React browser me frontend hai; Node (aksar Express ke saath) backend — server chalata hai, MongoDB se baat karta hai, React ko JSON bhejta hai. Agar frontend side bhi tumse poocha ja raha hai to React interview questions ka 7-din plan saath me revise kar lena.

Cluster 2 — Event Loop (Yahin Sabse Zyada Log Girte Hain)

Analogy se shuru karo, phir technical. Ek bank socho jisme ek hi teller hai. Slow kaam (loan verification) wo back-office ko de deta hai aur agla customer serve karta rehta hai. Ek teller, phir bhi line kabhi jamti nahi. Wahi teller = tumhara JS thread.

Q. Event loop ke phases kya hain? Order me: timers (setTimeout / setInterval) → pending callbacks (kuch deferred system callbacks) → poll (I/O callbacks — asli kaam yahin hota hai) → check (setImmediate) → close (jaise socket band hona). Beech me kuch internal phases bhi hain, par interview me yeh paanch bolna standard aur sufficient hai.

Q. Aur microtasks? Yeh wo line hai jo tumhe baaki candidates se alag karti hai: har phase ke beech Node pehle poori process.nextTick queue drain karta hai, phir Promise microtask queue (.then, queueMicrotask). Yaani nextTick hamesha promises se pehle, aur dono kisi bhi timer ya setImmediate se pehle.

Yaad rakhne ka formula:

sync code → process.nextTick → Promise microtasks → timers / setImmediate

Q. Iska output kya hoga?

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
process.nextTick(() => console.log('4'));
console.log('5');

Trace karke bolo, ratta mat maro:

  1. console.log('1') — synchronous, turant chalta hai.
  2. setTimeout — callback timers phase ke liye queue ho gaya, abhi nahi chalega.
  3. .then — microtask queue me chala gaya.
  4. process.nextTick — nextTick queue me, jo microtasks se pehle drain hoti hai.
  5. console.log('5') — abhi bhi synchronous, isliye upar wale sab queued callbacks se pehle.

Output: 1, 5, 4, 3, 2.

Q. setTimeout(fn, 0) aur setImmediate me kaun pehle? Yeh trick question hai. Top level par order guaranteed nahi hai — file kai baar chalao, order flip hota dikhega, kyunki yeh process startup ki timing par depend karta hai. Par kisi I/O callback ke andar setImmediate hamesha pehle chalta hai, kyunki loop tab timers se aage nikal chuka hota hai aur agla check phase hi hit karta hai. Jo candidate confidently "setTimeout pehle" bolta hai, wo galat bolta hai.

Cluster 3 — Callback → Promise → Async/Await

Q. Error-first callback kya hai? Node ki purani convention: callback ka pehla argument error hota hai (null agar sab theek), data uske baad — (err, data) => {}. Isliye tum hamesha if (err) pehle check karte ho, uske baad data chhoote ho.

Q. Callback hell kya hai aur promises ne kya fix kiya? Callbacks ke andar callbacks nest karte jao to code right ki taraf bhagta hai — "pyramid of doom". Promises ne use .then().then().catch() chain me flatten kiya, aur async/await ne aakhir me async code ko normal top-to-bottom code jaisa padhne layak bana diya, errors ke liye simple try/catch ke saath.

Q. Purani callback-based API ko promise me kaise badloge? util.promisify(fn) — bas condition yeh hai ki wo function error-first convention follow karta ho. Aur Node ab promise-native core bhi deta hai: fs.promises (ya 'fs/promises' se import) — seedha await fs.readFile(...), koi wrapping nahi.

Q. (Bahut poocha jaata hai) Yeh code slow kyun hai?

const a = await fsp.readFile('a.txt', 'utf8');
const b = await fsp.readFile('b.txt', 'utf8');

Kyunki a khatam hone se pehle b shuru hi nahi hota — total time = a + b. Dono independent hain, isliye saath fire karo:

const [a, b] = await Promise.all([
  fsp.readFile('a.txt', 'utf8'),
  fsp.readFile('b.txt', 'utf8'),
]);

Ab total time sirf slower wale ka. Rule: sequential await tabhi jab agla step pichle ka result use karta ho.

Q. forEach ke andar await kyun kaam nahi karta? forEach apne callback se return hui promises ko ignore kar deta hai — wo wait karta hi nahi. Isliye tumhara console.log khaali array print karta hai jabki awaits abhi pending hain. Fix: for...of loop (sequential) ya Promise.all(arr.map(...)) (parallel).

Cluster 4 — Modules: CommonJS vs ESM

Q. CommonJS aur ESM me farq? CommonJS = require / module.exports, synchronous (require file load hone tak block karta hai), Node ka historical default, aur har module first load ke baad cache ho jaata hai. ESM = import / export, static aur asynchronous, package.json me "type": "module" se ya .mjs file se on hota hai, aur top-level await plus tree-shaking support karta hai.

Q. Ek hi file ko do jagah require karo to do object milte hain? Nahi — wahi ek object dono jagah. CommonJS module ko cache kar leta hai. Isi wajah se shared db.js ya config.js apne aap singleton ban jaata hai — ek hi DB connection sab routes me.

Q. Classic gotcha — exports = { foo } kyun tootta hai? Kyunki exports sirf ek local reference hai jo shuru me module.exports ko point karta hai. Use mutate karna chalta hai (exports.foo = 1), par reassign karne se local variable kahin aur point karne lag jaata hai aur link toot jaata hai — Node abhi bhi original module.exports return karta hai, isliye caller ko {} milta hai. Rule: poora export replace karna ho to hamesha module.exports = ....

Cluster 5 — Streams Aur Buffers

Q. Stream kya hai aur kyun chahiye? Balti ek saath nahi pi sakte, straw se sip karte ho. Stream wahi straw hai — data ko chunk by chunk process karta hai, poori file memory me load kiye bina. Isi wajah se Node bade files, uploads aur video me strong hai.

Q. Stream ke types? Chaar — Readable (file read, req), Writable (file write, res), Duplex (dono, jaise TCP socket), Transform (duplex jo data ko beech me badalta hai, jaise gzip).

Q. pipe() aur pipeline() me kya farq? readable.pipe(writable) chunks apne aap flow kara deta hai aur backpressure handle karta hai (writable slow ho to readable ko "ruk ja" signal). Par pipe() errors handle nahi karta — readable error de de to destination writable apne aap band nahi hota, aur tumhara file handle ya socket leak ho jaata hai. Isliye real code me stream.pipeline() use karo: wo poori chain jodta hai, errors forward karta hai aur failure par har stream destroy karta hai. Promise form best hai — const { pipeline } = require('node:stream/promises') phir await pipeline(src, gzip, dest) ek try/catch ke andar.

Q. Buffer kya hai? Raw binary bytes ka fixed-length container. Buffer.from('hello') ya Buffer.alloc(10) se banta hai, aur buf.toString('utf-8') se text me decode hota hai. Buffers isliye hain kyunki file aur network data raw bytes hote hain, aur JS strings arbitrary binary safely hold nahi kar sakti.

Cluster 6 — Error Handling (Yeh Round Filter Karta Hai)

Q. Node me errors kaise catch karte ho? Ek hi tareeka nahi hai — async style ke hisaab se badalta hai:

Style Catch kaise
Error-first callback if (err) pehle check karo
Promise .catch()
async/await try / catch
EventEmitter / stream .on('error', ...)

Q. 'error' event handle na karo to kya hota hai? Agar EventEmitter ya stream 'error' emit kare aur koi listener na ho, to Node throw karta hai aur poora process crash ho jaata hai — sirf wo ek request nahi, baaki sab users ki requests bhi saath jaati hain. Isliye rule: emitter/stream fail hone se pehle hi 'error' listener attach karo.

Q. uncaughtException aur unhandledRejection ka sahi use kya hai? Sirf last resort — log karo aur clean shutdown karo (process.exit(1), process manager restart kar dega). Inhe error nigal ke chalte rehne ke liye mat use karo, kyunki us waqt process unknown/corrupt state me hota hai.

Q. Operational error vs programmer error? Operational = expected runtime failure (file missing, network down, bad user input) — isko handle karo. Programmer error = bug (jaise undefined par call) — isko crash hone do aur fix karo. Yeh distinction bol dena senior-level lagta hai.

Cluster 7 — REST API Aur Express Touchpoint

Q. Bina Express ke server bana sakte ho? Haan — core http module se: http.createServer((req, res) => {...}) aur server.listen(3000). Yahan req ek Readable stream hai aur res ek Writable stream. Yehi wajah hai ki POST body ko tumhe chunks me collect karna padta hai — wo ek stream hi to hai.

Q. To phir Express kyun? Express raw http ke upar routing, middleware chain, body parsing, aur error handling ko standard bana deta hai. Answer me framing yeh rakho: "Express koi jaadu nahi karta, wo http module ke upar ek patli layer hai jo boilerplate hata deti hai."

Q. Middleware kya hai? Ek function jo (req, res, next) leta hai, request ke beech me chalta hai, aur ya to response bhej deta hai ya next() call karke chain aage badha deta hai — jaise auth check, logging, validation. Error middleware alag hai: uske chaar parameters hote hain — (err, req, res, next) — aur Express usi signature se use pehchanta hai.

Q. Ek chhota REST API design karo — Todo app.

Method Route Kaam
GET /todos saari todos
GET /todos/:id ek todo
POST /todos nayi banao (201 return)
PUT / PATCH /todos/:id update
DELETE /todos/:id delete

Interviewer aage yeh poochta hai: galat id pe kya status code (404), validation fail pe kya (400), server crash pe kya (500), aur secrets kahan rakhoge — answer: environment variables (process.env), code me hardcode kabhi nahi, .env file .gitignore me.

Aage Kya Karna Hai

Yeh saat cluster fresher Node interview ka lagbhag poora surface cover kar dete hain. Par padh lena aur bol pana do alag cheezein hain — pressure me tumhara event loop wala answer tab hi nikalega jab tum use zubaan se 4-5 baar bol chuke ho.

To plan yeh rakho:

  1. Har cluster ka ek din. Notes band karke, apne aap ko zor se answer bolo.
  2. Har theory answer ke saath apne project ka ek example jodo — "maine apne API me pipeline use kiya tha kyunki..." — theory + project wala answer hamesha jeetta hai.
  3. Poore question bank, code walkthrough aur practice ke liye Node chapter khol lo — yahi blog ka structured, deep version hai.
  4. Phir AI mock interview me ek round do — bol ke, awaaz me. Wahi asli test hai ki answer sach me aata hai ya sirf padha hua hai.

Node ka interview yaad-shakti ka test nahi hai, samajh ka hai. Ek baar event loop clear ho gaya, to baaki sab uske upar apne aap baith jaata hai.

FAQ

Fresher Node.js interview me sabse zyada kya poocha jaata hai?

Sabse common cluster hai — Node kya hai (runtime, V8, non-blocking), event loop kaise kaam karta hai, callback se async/await tak ka safar, CommonJS vs ESM, aur ek chhota REST API design. Iske baad interviewer aksar tumhare apne project pe chala jaata hai, isliye jo backend tumne banaya hai uska har route aur har decision explain karne layak hona chahiye.

Node.js single-threaded hai — yeh answer poora kaise dein?

Sirf itna mat bolo ki 'Node single-threaded hai'. Sahi answer yeh hai ki tumhari JavaScript ek hi thread par chalti hai, par wait us thread par hota hi nahi. Network I/O ko OS kernel khud watch karta hai (epoll, kqueue, IOCP) aur uske liye koi extra thread nahi lagta. Sirf fs, dns.lookup, zlib aur heavy crypto libuv ke worker pool (default 4 threads) par jaate hain. Dono case me JS thread khaali wait me nahi baithta.

Event loop ka answer kitna deep dena chahiye fresher level pe?

Phases naam se bata do — timers, pending callbacks, poll, check, close — aur yeh add karo ki har phase ke beech Node pehle process.nextTick queue drain karta hai, phir Promise microtasks. Itna hi fresher ke liye kaafi strong answer hai. Ratta maar ke bolne se accha hai ek chhota code snippet ka output trace karke dikha do.

setTimeout(fn, 0) aur setImmediate me kaun pehle chalta hai?

Top level par iska order guaranteed nahi hai — file ko kai baar chalao to order flip hota dikhega, kyunki yeh process startup timing par depend karta hai. Par kisi I/O callback ke andar setImmediate hamesha pehle chalta hai, kyunki loop tab timers phase se aage nikal chuka hota hai aur seedha check phase hit karta hai. Interview me 'guaranteed nahi, except inside I/O' bolna hi sahi answer hai.

Node.js interview ke liye Express aana zaroori hai?

Haan, MERN ya backend fresher role ke liye lagbhag zaroori hai. Core http module se ek chhota server bana lena aur Express me routes, middleware (req, res, next) aur error middleware (err, req, res, next) samajhna — itna minimum hai. Bonus yeh hota hai ki tum bata sako ki Express ne raw http module ke upar kya cheez easy ki.

Node interview ki taiyari kitne din me ho sakti hai?

Agar tumne pehle se ek chhota REST API bana rakha hai, to 7 se 10 din ka focused revision kaafi hai — roz 2-3 ghante, ek din me ek cluster. Bilkul zero se shuru kar rahe ho to pehle ek CRUD API banao, phir theory ke upar jao, warna answers kitaabi lagenge aur follow-up question par phans jaoge.

Aage padho