DEV Community

Krati Joshi
Krati Joshi

Posted on

🚀 Day 11 of My Node.js Learning Journey: Understanding Events & EventEmitter

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");
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Developer!
Enter fullscreen mode Exit fullscreen mode

🔥 Common EventEmitter Methods

on()

Registers a listener for an event.

emitter.on("login", () => {
  console.log("User Logged In");
});
Enter fullscreen mode Exit fullscreen mode

emit()

Triggers an event and executes all registered listeners.

emitter.emit("login");
Enter fullscreen mode Exit fullscreen mode

once()

Runs the listener only the first time the event is emitted.

emitter.once("welcome", () => {
  console.log("Welcome!");
});
Enter fullscreen mode Exit fullscreen mode

✅ Passing Data with Events

emitter.on("login", (username) => {
  console.log(`Welcome ${username}`);
});

emitter.emit("login", "Krati");
Enter fullscreen mode Exit fullscreen mode

✅ 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");
Enter fullscreen mode Exit fullscreen mode

⚠️ 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"));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 events module.
  • 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 process object all use EventEmitter internally.

📚 What I Learned Today

  • ✔️ What events are in Node.js
  • ✔️ How EventEmitter works
  • ✔️ Difference between on(), emit(), and once()
  • ✔️ Passing data through events
  • ✔️ Handling multiple listeners
  • ✔️ Why the error event 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)