π 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
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
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.