NODE-JS PART 4: ARCHITECTURE

NODE-JS PART 4: ARCHITECTURE

1️⃣ JavaScript Main Thread (Top) This is where your code runs. Your console.log, functions, callbacks Only one thread Can do one thing at a time ⚠️ If this thread is busy, nothing else runs --- 2️⃣ Event Loop (Brain of Node.js) The event loop decides what runs next on the main thread. Inside it you see: 🔹 Callback Queues These hold callbacks waiting to run: Timers (setTimeout) I/O callbacks (file, network) Other async callbacks They are executed FIFO (first in, first out). --- 🔹 Microtasks & process.nextTick() These have higher priority. process.nextTick Promises (then, catch) They run: 👉 immediately after the current code 👉 before moving to the next event loop phase --- 3️⃣ libuv (C/C++ Layer) This is where the real async magic happens. JavaScript never runs here. libuv handles: 🔹 Thread Pool A pool of background threads (default 4). Used for: File system (fs) DNS Crypto Compression These threads do heavy or blocking work. --- 🔹 System APIs Some tasks are sent directly to the OS: Network requests OS timers libuv talks to the OS on Node.js’s behalf. --- 4️⃣ Operating System (Bottom) This is the actual machine-level work. Disk reads Network packets Hardware drivers Kernel threads The OS: Executes the task Notifies libuv when done --- 5️⃣ How They Communicate (Full Flow) Let’s take fs.readFile() as an example: 1. JS code calls fs.readFile() 2. Event loop sends task to libuv 3. libuv sends work to: thread pool or OS kernel 4. File is read in the background 5. OS notifies libuv 6. libuv adds callback to event loop queue 7. Event loop runs callback on JS main thread 👉 JS is involved only at the start and the end --- 6️⃣ Why This Is Powerful JS stays fast and responsive Heavy work happens elsewhere Thousands of requests handled with one thread Perfect for APIs, servers, real-time apps 🚀 --- One Sentence Summary Node.js runs JavaScript on one thread, offloads heavy work to libuv and the OS, and uses the event loop to bring results back safely. -