Event-driven programming kya hoti hai Node.js me?
Node.js me event-driven programming ek aisa programming style hai jisme code ka execution events ke respond karne par hota hai, instead of sequentially line-by-line. Matlab, kuch action hone par (jaise request aana, file read hona, ya button click) event trigger hota hai aur uske corresponding function (callback) execute hota hai.
🔹 Key Points:
- Events ka concept
- Node.js me events hoti hain jaise
data received,connection established,error occurred. - Har event ke liye aap listener define kar sakte ho.
- Node.js me events hoti hain jaise
- Event Emitter
- Node.js me
EventEmitterclass hai jo events create aur handle karne me help karta hai. - Aap events ko emit karte ho aur usko listener se handle karte ho.
- Node.js me
🔹 Example:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Event listener
myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
// Event trigger (emit)
myEmitter.emit('greet', 'Tirithraj');
Output:
Hello, Tirithraj!
greetevent ko trigger karte hi uska listener run hua.
🔹 Node.js me Event-driven programming ka use
- Server Requests: Jab HTTP request aati hai, server event trigger karta hai aur response send karta hai.
- Streams: Data chunks aane par event trigger hota hai.
- Asynchronous Operations: File read, DB query, network request me callback ke through event-driven execution hota hai.
Leave a Reply