title | displayTitle | description | authors | category |
---|---|---|---|---|
the-nodejs-events-module |
The Node.js events module |
The events module of Node.js provides the EventEmitter class |
flaviocopes, ZYSzys, MylesBorins, fhemberger, LaRuaNa, amiller-gh, ahmadawais |
learn |
The events
module provides us the EventEmitter class, which is key to working with events in Node.js.
const EventEmitter = require('events');
const door = new EventEmitter();
The event listener has these in-built events:
newListener
when a listener is addedremoveListener
when a listener is removed
Here's a detailed description of the most useful methods:
Alias for emitter.on()
.
Emits an event. It synchronously calls every event listener in the order they were registered.
door.emit('slam'); // emitting the event "slam"
Return an array of strings that represent the events registered on the current EventEmitter
object:
door.eventNames();
Get the maximum amount of listeners one can add to an EventEmitter
object, which defaults to 10 but can be increased or lowered by using setMaxListeners()
door.getMaxListeners();
Get the count of listeners of the event passed as parameter:
door.listenerCount('open');
Gets an array of listeners of the event passed as parameter:
door.listeners('open');
Alias for emitter.removeListener()
added in Node.js 10
Adds a callback function that's called when an event is emitted.
Usage:
door.on('open', () => {
console.log('Door was opened');
});
Adds a callback function that's called when an event is emitted for the first time after registering this. This callback is only going to be called once, never again.
const EventEmitter = require('events');
const ee = new EventEmitter();
ee.once('my-event', () => {
// call callback function once
});
When you add a listener using on
or addListener
, it's added last in the queue of listeners, and called last. Using prependListener
it's added, and called, before other listeners.
When you add a listener using once
, it's added last in the queue of listeners, and called last. Using prependOnceListener
it's added, and called, before other listeners.
Removes all listeners of an EventEmitter
object listening to a specific event:
door.removeAllListeners('open');
Remove a specific listener. You can do this by saving the callback function to a variable, when added, so you can reference it later:
const doSomething = () => {};
door.on('open', doSomething);
door.removeListener('open', doSomething);
Sets the maximum amount of listeners one can add to an EventEmitter
object, which defaults to 10 but can be increased or lowered.
door.setMaxListeners(50);