Event Emitters in Bun
×


Event Emitters in Bun

920

🔔 Introduction to Event Emitters in Bun

Events are at the heart of modern backend systems — from handling async operations to decoupling business logic. Just like Node.js, Bun also supports an EventEmitter-style pattern, thanks to its compatibility with Node's core modules.

In this tutorial, we’ll explore how to use event emitters in Bun for clean and modular app architecture 🚀.

🎯 What is an Event Emitter?

An Event Emitter is an object that allows us to register listeners for named events and emit those events asynchronously.

Think of it like a custom pub-sub system:

  • 📢 Emit events when something happens
  • 👂 Listeners respond to those events

⚙️ Setting Up EventEmitter in Bun

Bun includes the events module, which is compatible with Node.js.

You can import and use it just like in a Node environment.

import { EventEmitter } from "events";

const emitter = new EventEmitter();
That’s it! You're now ready to create custom events in Bun 💥.

🛠️ Creating and Emitting Events

Let’s build a simple event-driven example. Imagine we have a "user:created" event:

emitter.on("user:created", (user) => {
  console.log(`🎉 New user created: ${user.name}`);
});

function createUser(name) {
  const user = { id: Date.now(), name };
  emitter.emit("user:created", user);
}

createUser("Alice");
The listener waits for the user:created event, and once emitted, logs a message. This approach keeps our code modular and maintainable 🧩.

🔁 Listening Once with once()

Sometimes, you want to listen to an event just once.

Bun’s EventEmitter supports that too!

emitter.once("system:init", () => {
  console.log("🧪 System initialized only once!");
});

emitter.emit("system:init");
emitter.emit("system:init"); // This won't trigger again

âš¡ Real-World Use Case: Logging System

Let’s simulate a logging system that listens to events from different parts of the app:

function logEvent(type, message) {
  emitter.emit("log", { type, message });
}

emitter.on("log", ({ type, message }) => {
  console.log(`[${type.toUpperCase()}] - ${message}`);
});

logEvent("info", "Bun app started");
logEvent("error", "Something went wrong!");
You can now fire logs from anywhere in the app using the same interface 📊.

🧹 Removing Event Listeners

To prevent memory leaks, especially in long-running apps, it’s good to remove listeners when they’re no longer needed:

function tempHandler() {
  console.log("Temporary event.");
}

emitter.on("temp", tempHandler);
emitter.removeListener("temp", tempHandler);
You can also use emitter.removeAllListeners() to clear everything for a specific event.

📈 Advanced: Async Event Handling

Event listeners can be async too. Bun handles this efficiently, just like Node.js:

emitter.on("data:received", async (payload) => {
  await Bun.sleep(1000); // simulate delay
  console.log("📦 Data processed:", payload);
});

emitter.emit("data:received", { id: 101, value: "test" });
This makes it easy to plug event-driven logic into services like queues, logs, or notifications.

🔒 Best Practices for Event Emitters

  • 🧠 Use clear and consistent event names like user:created, log:error
  • 🔄 Avoid too many nested emitters — keep things modular
  • 📦 Consider a central event bus in larger apps
  • 🧪 Always test events thoroughly for both sync and async behavior

🏁 Final Thoughts

Event Emitters in Bun provide a simple yet powerful way to decouple your code, making it cleaner, more maintainable, and ready for scale 🚀.

Whether you're building real-time features, background processing, or just keeping concerns separated — emitters are a tool you’ll love using.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat