Explain the event-driven architecture in Node.js
Event-driven architecture in Node.js means the system responds to events (actions) instead of executing code step-by-step in a blocking way.
⚡ Simple Idea
Think of it like:
“When something happens → trigger a function”
Example:
- User clicks button → event fired
- File is read → event fired
- API request comes → event fired
🔁 How It Works Internally
1. Event Loop (Heart of Node.js)
- Continuously listens for events
- Picks tasks from queue
- Executes them one by one (non-blocking)
2. Event Emitter
Node.js has a built-in module called:
👉 EventEmitter
It allows you to:
- Emit events (trigger)
- Listen to events (handle)
🔧 Example
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Listen
emitter.on('login', () => {
console.log('User logged in');
});
// Emit
emitter.emit('login');
👉 Output: User logged in
🧠 Real-World Flow
Example: API Request
- Request comes to server
- Event loop receives it
- Sends it to handler
- Non-blocking I/O (DB call, file read)
- When done → callback/Promise executed
⚡ Why It’s Powerful
✅ Non-blocking
- Handles multiple users at once
✅ Scalable
- Ideal for real-time apps (chat, streaming)
✅ Efficient
- Doesn’t waste time waiting
🚨 Important Interview Point
👉 Node.js uses:
- Single thread
- But handles multiple concurrent requests
How?
→ Because of event-driven + async I/O
🔥 Real-World Example
Chat App
- User sends message → event triggered
- Server listens → broadcasts to others
💡 One-Line Answer (For Interview)
“Event-driven architecture in Node.js is a design pattern where the system reacts to events using the event loop and non-blocking I/O, enabling high scalability and concurrency.”