01 Introduction to Node.js
Node.js aaj ke time me Backend Development ka king hai. Lekin ye hai kya? Aaiye simple bhasha me samjhte hain.
Node.js Kya Hai?
Sabse pehle ye clear kar lein: Node.js koi Language nahi hai! 🚫 Node.js ek Runtime Environment hai jo JavaScript ko Browser ke bahar run karne ki taqat deta hai.
Pehle JavaScript sirf browser (Chrome, Firefox) me chalti thi. Ryan Dahl ne socha, “Kyun na JS ko server par run karein?” aur aise Node.js ka janm hua.
Architecture: Under the Hood ⚙️
Node.js powerful kyun hai? Kyunki ye V8 Engine aur Libuv library par bana hai.
1. V8 Engine (Google ka Powerhouse)
Ye wahi engine hai jo Google Chrome me JavaScript run karta hai. Node.js is engine ko C++ ke sath embed karta hai taaki JS code machine code me convert ho sake aur super fast chale.
2. Single Threaded Event Loop
Node.js Single Threaded hai. Matlab ye ek baar me ek hi kaam karta hai? Haan aur Nahi. Iska main thread (Event Loop) single hai, lekin ye background tasks (file reading, DB queries) ko system ke doosre threads ko de deta hai.
Real-world Example (Restaurant Analogy): 🍽️
-
Multithreaded (Java/PHP/Python):
- Ek waiter aata hai, order leta hai, aur kitchen me khada rehta hai jab tak order ready na ho.
- Doosre customer ke liye naya waiter chahiye. (Resource heavy)
-
Node.js (Event Loop):
- Ek hi super-fast waiter hai.
- Order leta hai -> Kitchen me pachi deta hai -> Turant doosre table par chala jata hai.
- Jab kitchen se “Tring Tring” (Event) aati hai, wo order serve kar deta hai.
- Result: Ek waiter hazaron customers handle kar sakta hai!
Blocking vs Non-Blocking Code
Node.js Non-Blocking I/O use karta hai.
❌ Blocking Code (Ouch!)
Ye code execution ko rok deta hai jab tak file read na ho jaye.
const fs = require('fs');const data = fs.readFileSync('/file.md'); // Yahan code ruk jayegaconsole.log(data);console.log("Ye line file read hone ke baad hi chalegi");✅ Non-Blocking Code (Super Fast!)
Ye callback ka use karta hai aur aage badh jata hai.
const fs = require('fs');fs.readFile('/file.md', (err, data) => { if (err) throw err; console.log(data); // Jab file read hogi tab ye chalega});console.log("Ye line pehle print hogi!"); // Code rukega nahiKab Node.js Use Karein?
| Use Karein ✅ | Use Na Karein ❌ |
|---|---|
| Real-time Apps (Chat, Gaming) | CPU Intensive Apps (Video Encoding) |
| API Servers (JSON APIs) | Machine Learning (Python is better) |
| Streaming Apps (Netflix style) | Complex Computations |
Summary
Node.js JavaScript ko server par laata hai. Ye Non-blocking aur Event-driven hai, jo isse I/O operations (Database, Network) ke liye bohot tez banata hai.
Next Up: Chaliye dekhte hain Node.js ke built-in weapons - Core Modules! 🛠️