Event Emitters in Bun
0 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!

Share:
Comments
Waiting for your comments