One of the biggest reasons Node.js is so powerful is its event-driven architecture. Today, I learned how Node.js uses events to build scalable and loosely coupled applications.
💡 What are Events?
An event is an action or occurrence that happens during the execution of a program. Instead of constantly checking whether something has happened, Node.js waits for an event and reacts when it occurs.
Examples:
- User logs in
- HTTP request reaches the server
- File reading completes
- Database connection is established
- Timer finishes
📌 EventEmitter
Node.js provides the built-in EventEmitter class from the events module to create and handle custom events.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("greet", () => {
console.log("Hello, Developer!");
});
emitter.emit("greet");
Output:
Hello, Developer!
🔥 Common EventEmitter Methods
✅ on()
Registers a listener for an event.
emitter.on("login", () => {
console.log("User Logged In");
});
✅ emit()
Triggers an event and executes all registered listeners.
emitter.emit("login");
✅ once()
Runs the listener only the first time the event is emitted.
emitter.once("welcome", () => {
console.log("Welcome!");
});
✅ Passing Data with Events
emitter.on("login", (username) => {
console.log(`Welcome ${username}`);
});
emitter.emit("login", "Krati");
✅ Multiple Listeners
A single event can notify multiple independent listeners.
emitter.on("orderPlaced", () => console.log("Inventory Updated"));
emitter.on("orderPlaced", () => console.log("Email Sent"));
emitter.on("orderPlaced", () => console.log("Invoice Generated"));
emitter.emit("orderPlaced");
⚠️ The Special error Event
The "error" event is treated specially in Node.js. If it is emitted without an error listener, the application may terminate.
emitter.on("error", (err) => {
console.error(err.message);
});
emitter.emit("error", new Error("Something went wrong"));
Always register an "error" listener when emitting error events.
🌍 Real-World Example
Imagine an e-commerce application:
Order Placed
│
├── Update Inventory
├── Send Confirmation Email
├── Generate Invoice
├── Notify Admin
└── Reward Loyalty Points
Instead of calling every function manually, the application emits a single orderPlaced event, and different modules respond independently. This makes the system easier to maintain and extend.
🎯 Interview Takeaways
- EventEmitter is provided by the built-in
eventsmodule. -
on()registers a listener. -
emit()triggers an event. -
once()executes only once. - One event can have multiple listeners.
- EventEmitter listeners execute synchronously by default.
- The
"error"event should always have an error listener. - EventEmitter is different from the Event Loop.
- Streams, HTTP servers, and the
processobject all use EventEmitter internally.
📚 What I Learned Today
- ✔️ What events are in Node.js
- ✔️ How EventEmitter works
- ✔️ Difference between
on(),emit(), andonce() - ✔️ Passing data through events
- ✔️ Handling multiple listeners
- ✔️ Why the
errorevent is important - ✔️ Real-world use cases of EventEmitter
- ✔️ Why Node.js follows an event-driven architecture
💭 Final Thoughts
Events are one of the core concepts that make Node.js efficient and scalable. By using EventEmitter, different parts of an application can communicate without being tightly connected, making code cleaner, more modular, and easier to maintain.
I'm excited to continue exploring more Node.js concepts in the coming days! 🚀
#NodeJS #JavaScript #BackendDevelopment #WebDevelopment #100DaysOfCode #OpenSource #Coding #EventEmitter #LearningInPublic #DevCommunity
Top comments (0)