Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The events module provides the EventEmitter class, which is used for event-driven code in Node.
For a full guide with examples, see the EventEmitter tutorial. This lesson summarizes the API.
const EventEmitter = require('events')
const door = new EventEmitter()
EventEmitter itself emits these events:
newListenerwhen a listener is addedremoveListenerwhen a listener is removed
Here is a summary of the most useful methods:
- emitter.addListener()
- emitter.emit()
- emitter.eventNames()
- emitter.getMaxListeners()
- emitter.listenerCount()
- emitter.listeners()
- emitter.off()
- emitter.on()
- emitter.once()
- emitter.prependListener()
- emitter.prependOnceListener()
- emitter.removeAllListeners()
- emitter.removeListener()
- emitter.setMaxListeners()
emitter.addListener()
Alias for emitter.on().
emitter.emit()
Emits an event. It synchronously calls every event listener in the order they were registered.
emitter.eventNames()
Returns an array of strings that represent the events registered on the current EventEmitter:
door.eventNames()
emitter.getMaxListeners()
Returns the maximum number of listeners (default 10). Change it with setMaxListeners().
door.getMaxListeners()
emitter.listenerCount()
Gets the count of listeners for the event passed as parameter:
door.listenerCount('open')
emitter.listeners()
Gets an array of listeners of the event passed as parameter:
door.listeners('open')
emitter.off()
Alias for emitter.removeListener() (added in Node 10).
emitter.on()
Adds a callback function that’s called when an event is emitted.
Usage:
door.on('open', () => {
console.log('Door was opened')
})
emitter.once()
Adds a callback that runs the first time the event is emitted after registration. The callback runs only once.
const EventEmitter = require('events')
const ee = new EventEmitter()
ee.once('my-event', () => {
// call callback function once
})
emitter.prependListener()
Listeners added with on or addListener are appended to the queue. With prependListener the listener is added (and called) before existing listeners.
emitter.prependOnceListener()
Listeners added with once are appended. With prependOnceListener the listener is added (and called) before existing listeners.
emitter.removeAllListeners()
Removes all listeners for a specific event:
door.removeAllListeners('open')
emitter.removeListener()
Removes a specific listener. You can do this by saving the callback function to a variable when adding it, so you can reference it later:
const doSomething = () => {}
door.on('open', doSomething)
door.removeListener('open', doSomething)
emitter.setMaxListeners()
Sets the maximum number of listeners (default 10).
door.setMaxListeners(50) Lessons in this unit:
| 0: | Introduction |
| 1: | ▶︎ The Node events module |
| 2: | The Node fs module |
| 3: | The Node http module |
| 4: | The Node os module |
| 5: | The Node path module |