Event Emitters in Node.js
In Node.js, an Event Emitter is a fundamental concept used to handle asynchronous events. It is part of the events
module, and it allows an object to emit events and allow listeners to respond to those events.
The EventEmitter
class in Node.js provides an interface for creating objects that can emit events and register event listeners (callbacks) for those events.
Key Concepts:
-
Emit: When something happens (an event occurs), an emitter can emit that event.
-
Listen: The system listens for events and executes specific code when the event is triggered.
-
Event Handling: Allows asynchronous handling of events.
How to Use Event Emitters
1. Import the events
module
To use event emitters, you first need to import the events
module.
2. Create an instance of EventEmitter
You create an instance of EventEmitter
using the new
keyword. Then, you can use this instance to emit events and add listeners.
3. Add Listeners to Events
You can listen for specific events using the .on()
method. When the event is emitted, the corresponding callback function is executed.
-
.on('event', callback)
is used to register an event listener. -
In the example, we're listening for the
greet
event and printing the passed message when it's triggered.
4. Emit Events
You can trigger (emit) an event using the .emit()
method. This will execute all the functions that are listening for that specific event.
-
.emit('event', ...)
triggers the event, and any listeners that are attached to that event are invoked.
Example: EventEmitter in Action
Here’s a complete example that demonstrates creating a custom event, adding listeners, and emitting the event.
Output:
Event Handling Flow:
-
The first listener listens for the
greet
event and logs the message. -
The second listener also listens for the
greet
event and logs the message again. -
When the event is emitted, both listeners are triggered, and the message is logged.
Other Methods Available for EventEmitters
-
.once(eventName, listener)
: Listens to an event only once and removes the listener after it is triggered. -
.removeListener(eventName, listener)
: Removes a specific listener for an event. -
.removeAllListeners([eventName])
: Removes all listeners for a particular event or for all events.
When to Use Event Emitters
Event Emitters are ideal for scenarios like:
-
Handling multiple async events.
-
Emitting events from custom objects (e.g., a server or a user action).