The events module of Node.js provides the EventEmitter class.
The events module provides us with the EventEmitter class, which is essential for working with events in Node. I have written a detailed article on this topic, which you can find here. In this blog, I will describe the API without providing further examples on how to use it.
const EventEmitter = require('events')
const door = new EventEmitter()
The EventEmitter class uses the following events internally:
newListener
: triggered when a listener is added.removeListener
: triggered when a listener is removed.
Here is a detailed description of the most useful methods:
emitter.addListener()
(alias foremitter.on()
): Adds a listener to an event.emitter.emit()
: Emits an event and calls every event listener in the order they were registered.emitter.eventNames()
: Returns an array of strings representing the registered events on the current EventEmitter instance.emitter.getMaxListeners()
: Gets the maximum number of listeners that can be added to an EventEmitter object. The default value is 10 but can be increased or decreased usingsetMaxListeners()
.emitter.listenerCount()
: Gets the count of listeners for a specific event.emitter.listeners()
: Returns an array of listeners for a specific event.emitter.off()
(alias foremitter.removeListener()
): Removes a specific listener from the EventEmitter.emitter.on()
: Adds a callback function to be called when an event is emitted.emitter.once()
: Adds a callback function to be called only for the first occurrence of an event.emitter.prependListener()
: Adds a listener to the beginning of the listeners queue for an event.emitter.prependOnceListener()
: Adds a listener to be called before other listeners when an event is emitted for the first time.emitter.removeAllListeners()
: Removes all listeners for a specific event from the EventEmitter object.emitter.removeListener()
: Removes a specific listener from the EventEmitter object. The callback function can be referenced using a variable.emitter.setMaxListeners()
: Sets the maximum number of listeners that can be added to an EventEmitter object.
Tags: Node.js, events module, EventEmitter