The Node Event Emitter: Working with Custom Events in Node
If you have experience working with JavaScript in the browser, you know how important events are for handling user interactions such as mouse clicks, keyboard button presses, and mouse movements. On the backend side, Node provides us with the events
module to build a similar event system.
The events
module includes the EventEmitter
class, which we can use to handle our custom events. To use it, simply initialize an EventEmitter
object:
1 | const EventEmitter = require('events'); |
Now, you have access to various methods of the EventEmitter
object, including on
and emit
.
The emit
method is used to trigger an event, while the on
method is used to add a callback function that will be executed when the event is triggered.
Here’s an example of creating a start
event and adding a callback function to log a message to the console when the event is triggered:
1 | eventEmitter.on('start', () => { |
To trigger the start
event and execute the callback function, use the emit
method:
1 | eventEmitter.emit('start'); |
You can also pass arguments to the event handler by including them as additional arguments in the emit
method. For example:
1 | eventEmitter.on('start', (number) => { |
Multiple arguments can be passed to the event handler as well:
1 | eventEmitter.on('start', (start, end) => { |
If you only want an event listener to be executed once, you can use the once
method:
1 | eventEmitter.once('start', () => { |
To remove an event listener, you can use the removeListener
method. However, you need to have a reference to the callback function that was added using on
. Here’s an example:
1 | eventEmitter.on('start', () => { |
If you want to remove all listeners for a specific event, you can use removeAllListeners
:
1 | eventEmitter.removeAllListeners('start'); |
You can also retrieve the events registered on an EventEmitter
instance using eventNames
:
1 | eventEmitter.on('start', () => { |
To get the count of listeners for an event, you can use listenerCount
:
1 | eventEmitter.listenerCount('start'); // Output: 1 |
When you have multiple listeners, the order in which they are executed can be important. The EventEmitter
object provides two methods to work with the order of listeners:
emitter.prependListener()
: Adds a listener at the beginning of the queue, making it the first listener to be called.emitter.prependOnceListener()
: Adds a listener at the beginning of the queue for a one-time event.
By utilizing these methods, you can control the order of execution for your listeners and handle events more precisely.
Tags: Node.js, events, EventEmitter, event handling