Event Emitters in Bun
×


Event Emitters in Bun

105

๐Ÿ”” 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 blog, 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

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat