What is Node.js & the Event Loop?
⚡ What is Node.js & the Event Loop
🌐 What is Node.js?
Node.js is:
- A JavaScript runtime — runs JavaScript code outside the browser
- Built on Chrome's V8 engine — the same high-performance JavaScript engine that powers Google Chrome
- Event-driven — built around an event loop for handling asynchronous operations
- Non-blocking I/O — performs file/network operations without blocking execution
- Single-threaded — your JavaScript runs on a single thread (though Node uses threads behind the scenes for I/O)
Browser JavaScript vs Node.js
Browser (Client-Side)
- Runs in the user's browser
- Accesses DOM, local storage
- Handles user interactions
- Limited file system access
- Same-origin policy restrictions
Node.js (Server-Side)
- Runs on servers/your machine
- Full file system access
- No DOM (no UI)
- Database/network operations
- Environment variables, secrets
🔄 The Event Loop: The Heart of Node.js
The event loop is Node.js's execution model. It allows Node.js to handle thousands of concurrent connections without creating a thread for each one.
Call Stack
Where your synchronous code executes. Functions are pushed and popped as they run.
Event Loop
Checks if the call stack is empty, then processes callbacks from the queue.
Callback Queue
Where async callbacks (setTimeout, file reads, etc.) wait to be executed.
Non-Blocking
I/O operations don't pause execution — they're handled asynchronously.
⛔ Blocking vs Non-Blocking I/O
Two Approaches to File Reading
Blocking (❌ Don't do this)
Non-Blocking (✅ Do this)
📞 Callbacks: The Foundation of Async
A callback is a function passed to another function, to be called later when something happens:
▶️ Running Node.js
Your First Node.js Program
Run it:
Interactive REPL: Type `node` to enter the interactive shell:
💻 Coding Challenges
Challenge 1: Understanding Execution Order
Write a Node.js script that logs numbers in different orders using synchronous code, setTimeout, and callbacks. Predict the output before running it.
Goal: Internalize how the event loop affects execution order.
Challenge 2: Blocking vs Non-Blocking
Create two versions of a program that reads a file: one using readFileSync (blocking) and one using readFile (non-blocking). Measure which is faster when reading multiple files.
Goal: See non-blocking I/O in action.
Challenge 3: Callback Pattern
Write a function that accepts a callback and calls it with data from a file. Use error-first callbacks (error as first param). Test both success and error paths.
Goal: Master the callback pattern used throughout Node.js.
The golden rule of Node.js is: never block the event loop. Even a 1-second file read blocks everything. This is why non-blocking I/O is so important. Later chapters cover Promises and async/await, which make non-blocking code easier to read.
🎯 What's Next
Now that you understand what Node.js is and how the event loop works, we'll dive into Modules & npm — how to organize code and manage dependencies.