Event Emitter
Event Emitter
Event Emitter
developers.redhat.com | @RHDevelopers
This cheat sheet covers the basic principles around Node.js event emitters.
EVENT EMITTER
Node.js allows us to create and handle custom events easily by using the events
module. The Event module includes the EventEmitter class which can be used to
raise and handle custom events.
Some modules using the EventEmitter class:
myEmitter.removeAllListeners(['eventOne']); // receives an array of events
Http
Streams
EventEmitter.prototype.setMaxListeners()
Event Emitter Class Sets the maximum allowed listeners for a speci c event. Node.js will print a warning
if more than 10 listeners are added for a speci c event. setMaxListeners allows you
You can get the EventEmitter class from the Node.js built in events module. to modify this limit.
const { EventEmitter } = require('events'); myEmitter.setMaxListeners(25);
EventEmitter.prototype.on() Returns the current max listener value for the EventEmitter instance.
myEmitter = new EventEmitter();
Listens to a speci c event and its data.
myEmitter.on('eventOne', (data) => console.log(data.msg)); myEmitter.getMaxListeners() // defaults to 10
EventEmitter.prototype.addListener() EventEmitter.listenerCount()
Same as the myEmitter.on() method. Returns the number of listeners for a given event.
myEmitter.addListener('eventOne', (data) => console.log(data.msg)); const myEmitter = new EventEmitter();
Sets the default max listens for all EventEmitter instances. However, calling
EventEmitter.prototype.removeListener() emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.
const { defaultMaxListeners } = require('events');
Remove a listener from the listener array for the speci ed event.
defaultMaxListeners(25);
const callback = () => {
console.log('someone connected!');
};
myEmitter.on('connection', callback);
myEmitter.removeListener('connection', callback);
EventEmitter.prototype.removeAllListeners()