Node.js Architecture Explained
Node.js is famous for its speed and performance. But have you ever wondered why it is so fast?
The secret behind Node.js is the V8 Engine, single-threaded architecture, and the powerful event loop.
1. V8 Engine
Converts JavaScript into fast machine code.
console.log("Node.js runs on V8 Engine");
2. Single Thread
- Handles many users
- Low memory
- Fast
Single-thread ≠ single user
3. Blocking vs Non-Blocking
Blocking
const fs = require("fs");
const data = fs.readFileSync("file.txt", "utf-8");
console.log(data);
console.log("Done");
Non-Blocking
const fs = require("fs");
fs.readFile("file.txt", "utf-8", (err, data) => {
console.log(data);
});
console.log("Done");
4. Event Loop (Heart of Node.js)
The Event Loop is the core mechanism that allows Node.js to handle multiple operations using a single thread.
It continuously checks:
- Is the call stack empty?
- Are there callbacks waiting?
- Can a task be executed?
How It Works
- Code runs in Call Stack
- Async tasks go to background
- Callbacks move to Callback Queue
- Event Loop pushes them to stack
- Execution happens
Example
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 0);
console.log("End");
Output:
Start
End
Async Task
End
Async Task
Even with 0ms delay, async code runs after the call stack is empty.
Event Loop is the main reason Node.js is fast and non-blocking.
| Feature | Blocking | Non-Blocking |
|---|---|---|
| Execution | Waits | Does not wait |
| Speed | Slow | Fast |
Conclusion
Now you understand how Node.js uses the Event Loop to handle multiple tasks efficiently 🚀
Tags
NodeJS