How Node.js Works

Node.js is a <strong data-start="35" data-end="57" style="color: rgb(32, 30, 26);">JavaScript runtime</strong> that lets you run JavaScript outside the browser.&nbsp;

Lesson content

Node.js is a JavaScript runtime that lets you run JavaScript outside the browser. It is fast because it uses non-blocking I/O and an Event Loop to handle many requests at the same time. Real-Life Example 🍕 (Pizza Restaurant) Imagine a pizza restaurant. 👨‍🍳 Chef = V8 Engine (Runs JavaScript) 🙋 Waiter = Event Loop 👷 Kitchen Staff = libuv (Handles slow tasks) When a customer orders a pizza: The waiter takes the order. The chef starts preparing it. If another customer arrives, the waiter doesn't make them wait. The kitchen staff handles other work while the chef keeps cooking. When the pizza is ready, the waiter serves it. Node.js works the same way. Step 1: User Sends a Request Browser │ ▼ Node.js Server Example: GET /users Step 2: V8 Runs JavaScript The V8 Engine executes your JavaScript code. console . log( "Hello Node.js" ); Output Hello Node.js Step 3: Normal Code Runs Immediately console . log( "Start" ); console . log( "End" ); Output Start End Step 4: Slow Task (Reading a File) const fs = require ( "fs" ); console . log( "Start" ); fs . readFile( "data.txt" , () => { console . log( "File Loaded" ); }); console . log( "End" ); Output Start End File Loaded Why? Reading a file takes time. Instead of waiting, Node.js asks libuv to read the file and continues executing the next line. Step 5: libuv Handles Slow Work Tasks like: Reading files Database queries API calls Timers are handled by libuv . JavaScript │ ▼ libuv │ Reads File Step 6: Event Loop When the file is ready, the Event Loop checks if JavaScript is free. If yes, it runs the callback. File Ready │ ▼ Event Loop │ ▼ Callback Runs Complete Flow User Request │ ▼ Node.js Server │ ▼ V8 Executes JavaScript │ ▼ Need Slow Task? │ ┌────┴────┐ │ │ No Yes │ │ ▼ ▼ Continue libuv │ ▼ Task Complete │ ▼ Event Loop │ ▼ Execute Callback │ ▼ Send Response Why is Node.js Fast? ✅ Runs JavaScript with the V8 Engine ✅ Doesn't wait for slow tasks ✅ Uses libuv for background operations ✅ Uses the Event Loop to handle completed tasks ✅ Can serve many users without creating a new thread for each request Key Points to Remember Component Responsibility V8 Engine Executes JavaScript code libuv Handles slow operations (File System, Network, Timers) Event Loop Executes callbacks after async tasks finish Node.js Coordinates everything efficiently 🧠 Easy Formula Request ↓ V8 Runs JavaScript ↓ Slow Task? ↓ libuv ↓ Event Loop ↓ Callback ↓ Response Remember: Node.js is single-threaded for JavaScript execution , but it can handle many requests concurrently because it delegates slow I/O operations to libuv and uses the Event Loop to process results efficiently.