Mental Model and Event Loop
Single-threaded architecture, Event Loop, and Non-blocking I/O.
🧑🏫 Sabse pehle — simple mein samjho#
Browser mein JavaScript sirf UI handle karti hai. Node.js usi JavaScript engine (V8) ko nikal kar server pe daal deta hai taaki tum database connect kar sako aur files read kar sako. Node.js ek "Single-Threaded" worker hai. Iska matlab server pe sirf ek hi waiter hai jo sabka order (requests) leta hai. Lekin Node fast kyu hai? Kyunki ye "Non-blocking" hai. Waiter kitchen mein order dekar khada nahi rehta, wo fauran dusre table ka order lene chala jata hai. Jaise hi khana ready hota hai, kitchen se aawaz aati hai (Event/Callback) aur waiter khana serve kar deta hai. Is puri system ko Event Loop sambhalta hai.
Single-Threaded but Highly Concurrent#
Traditional backend languages like Java or PHP often create a new "thread" (a new worker) for every incoming user request. If 1000 users connect, 1000 threads are created, which eats up a lot of RAM.
Node.js uses a single main thread. However, it can handle thousands of concurrent connections because it offloads heavy tasks (like reading files, querying a database, or making network requests) to the operating system's background workers (the thread pool).
Non-Blocking I/O#
I/O stands for Input/Output. In Node, almost all I/O operations are non-blocking (asynchronous).
const fs = require('fs');
// ❌ Blocking (Synchronous) - BAD for web servers
const data = fs.readFileSync('/file.txt');
console.log("File reading finished");
console.log("This prints LAST");
// If the file takes 5 seconds to read, the ENTIRE server freezes for 5 seconds.
// ✅ Non-Blocking (Asynchronous) - GOOD
fs.readFile('/file.txt', (err, data) => {
console.log("File reading finished");
});
console.log("This prints FIRST");
// Node continues executing the next lines while the file is being read in the background.
The Event Loop (The Heart of Node.js)#
The Event Loop is what allows Node.js to perform non-blocking I/O operations despite being single-threaded. It constantly spins, checking if any background tasks have finished.
It operates in phases (simplified):
- Timers Phase: Executes callbacks scheduled by
setTimeoutandsetInterval. - Poll Phase: Retrieves new I/O events (like incoming HTTP requests or file read completions) and executes their callbacks. This is where Node spends most of its time.
- Check Phase: Executes callbacks scheduled by
setImmediate. - Close Callbacks Phase: Executes close events, like
socket.on('close').
(Note: Microtasks like Promises and process.nextTick are executed immediately after the current operation finishes, before the Event Loop moves to the next phase).
When NOT to use Node.js?#
Because the main thread handles all the JavaScript execution, Node.js is terrible for CPU-intensive tasks (like heavy video processing, complex math computations, or image resizing). If you block the main thread with a heavy for-loop, no other user can get a response from the server until that loop finishes!