Source Code: lib/events.js
Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called \"emitters\")\nemit named events that cause Function objects (\"listeners\") to be called.
Function
For instance: a net.Server object emits an event each time a peer\nconnects to it; a fs.ReadStream emits an event when the file is opened;\na stream emits an event whenever data is available to be read.
net.Server
fs.ReadStream
All objects that emit events are instances of the EventEmitter class. These\nobjects expose an eventEmitter.on() function that allows one or more\nfunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.
EventEmitter
eventEmitter.on()
When the EventEmitter object emits an event, all of the functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and discarded.
The following example shows a simple EventEmitter instance with a single\nlistener. The eventEmitter.on() method is used to register listeners, while\nthe eventEmitter.emit() method is used to trigger the event.
eventEmitter.emit()
import { EventEmitter } from 'node:events';\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
const EventEmitter = require('node:events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
The eventEmitter.emit() method allows an arbitrary set of arguments to be\npassed to the listener functions. Keep in mind that when\nan ordinary listener function is called, the standard this keyword\nis intentionally set to reference the EventEmitter instance to which the\nlistener is attached.
this
const myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n console.log(a, b, this, this === myEmitter);\n // Prints:\n // a b MyEmitter {\n // domain: null,\n // _events: { event: [Function] },\n // _eventsCount: 1,\n // _maxListeners: undefined } true\n});\nmyEmitter.emit('event', 'a', 'b');\n
It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n console.log(a, b, this);\n // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n
The EventEmitter calls all listeners synchronously in the order in which\nthey were registered. This ensures the proper sequencing of\nevents and helps avoid race conditions and logic errors. When appropriate,\nlistener functions can switch to an asynchronous mode of operation using\nthe setImmediate() or process.nextTick() methods:
setImmediate()
process.nextTick()
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n setImmediate(() => {\n console.log('this happens asynchronously');\n });\n});\nmyEmitter.emit('event', 'a', 'b');\n
When a listener is registered using the eventEmitter.on() method, that\nlistener is invoked every time the named event is emitted.
const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.on('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Prints: 2\n
Using the eventEmitter.once() method, it is possible to register a listener\nthat is called at most once for a particular event. Once the event is emitted,\nthe listener is unregistered and then called.
eventEmitter.once()
const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.once('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Ignored\n
When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as special cases\nwithin Node.js.
'error'
If an EventEmitter does not have at least one listener registered for the\n'error' event, and an 'error' event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
To guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the node:domain module is deprecated.)
domain
node:domain
As a best practice, listeners should always be added for the 'error' events.
const myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n console.error('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n
It is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol events.errorMonitor.
events.errorMonitor
import { EventEmitter, errorMonitor } from 'node:events';\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on(errorMonitor, (err) => {\n MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n
const { EventEmitter, errorMonitor } = require('node:events');\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on(errorMonitor, (err) => {\n MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n
Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:
async
const ee = new EventEmitter();\nee.on('something', async (value) => {\n throw new Error('kaboom');\n});\n
The captureRejections option in the EventEmitter constructor or the global\nsetting change this behavior, installing a .then(undefined, handler)\nhandler on the Promise. This handler routes the exception\nasynchronously to the Symbol.for('nodejs.rejection') method\nif there is one, or to 'error' event handler if there is none.
captureRejections
.then(undefined, handler)
Promise
Symbol.for('nodejs.rejection')
const ee1 = new EventEmitter({ captureRejections: true });\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst ee2 = new EventEmitter({ captureRejections: true });\nee2.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee2[Symbol.for('nodejs.rejection')] = console.log;\n
Setting events.captureRejections = true will change the default for all\nnew instances of EventEmitter.
events.captureRejections = true
import { EventEmitter } from 'node:events';\n\nEventEmitter.captureRejections = true;\nconst ee1 = new EventEmitter();\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n
const events = require('node:events');\nevents.captureRejections = true;\nconst ee1 = new events.EventEmitter();\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n
The 'error' events that are generated by the captureRejections behavior\ndo not have a catch handler to avoid infinite error loops: the\nrecommendation is to not use async functions as 'error' event handlers.
The EventTarget and Event objects are a Node.js-specific implementation\nof the EventTarget Web API that are exposed by some Node.js core APIs.
EventTarget
Event
const target = new EventTarget();\n\ntarget.addEventListener('foo', (event) => {\n console.log('foo event happened!');\n});\n
There are two key differences between the Node.js EventTarget and the\nEventTarget Web API:
The NodeEventTarget object implements a modified subset of the\nEventEmitter API that allows it to closely emulate an EventEmitter in\ncertain situations. A NodeEventTarget is not an instance of EventEmitter\nand cannot be used in place of an EventEmitter in most cases.
NodeEventTarget
listener
type
prependListener()
prependOnceListener()
rawListeners()
setMaxListeners()
getMaxListeners()
errorMonitor
'newListener'
'removeListener'
EventListener
Event listeners registered for an event type may either be JavaScript\nfunctions or objects with a handleEvent property whose value is a function.
handleEvent
In either case, the handler function is invoked with the event argument\npassed to the eventTarget.dispatchEvent() function.
event
eventTarget.dispatchEvent()
Async functions may be used as event listeners. If an async handler function\nrejects, the rejection is captured and handled as described in\nEventTarget error handling.
An error thrown by one handler function does not prevent the other handlers\nfrom being invoked.
The return value of a handler function is ignored.
Handlers are always invoked in the order they were added.
Handler functions may mutate the event object.
function handler1(event) {\n console.log(event.type); // Prints 'foo'\n event.a = 1;\n}\n\nasync function handler2(event) {\n console.log(event.type); // Prints 'foo'\n console.log(event.a); // Prints 1\n}\n\nconst handler3 = {\n handleEvent(event) {\n console.log(event.type); // Prints 'foo'\n }\n};\n\nconst handler4 = {\n async handleEvent(event) {\n console.log(event.type); // Prints 'foo'\n }\n};\n\nconst target = new EventTarget();\n\ntarget.addEventListener('foo', handler1);\ntarget.addEventListener('foo', handler2);\ntarget.addEventListener('foo', handler3);\ntarget.addEventListener('foo', handler4, { once: true });\n
When a registered event listener throws (or returns a Promise that rejects),\nby default the error is treated as an uncaught exception on\nprocess.nextTick(). This means uncaught exceptions in EventTargets will\nterminate the Node.js process by default.
Throwing within an event listener will not stop the other registered handlers\nfrom being invoked.
The EventTarget does not implement any special default handling for 'error'\ntype events like EventEmitter.
Currently errors are first forwarded to the process.on('error') event\nbefore reaching process.on('uncaughtException'). This behavior is\ndeprecated and will change in a future release to align EventTarget with\nother Node.js APIs. Any code relying on the process.on('error') event should\nbe aligned with the new behavior.
process.on('error')
process.on('uncaughtException')
The Event object is an adaptation of the Event Web API. Instances\nare created internally by Node.js.
This is not used in Node.js and is provided purely for completeness.
Alias for event.target.
event.target
Is true if cancelable is true and event.preventDefault() has been\ncalled.
true
cancelable
event.preventDefault()
The <AbortSignal> \"abort\" event is emitted with isTrusted set to true. The\nvalue is false in all other cases.
\"abort\"
isTrusted
false
The millisecond timestamp when the Event object was created.
The event type identifier.
Alias for event.stopPropagation(). This is not used in Node.js and is\nprovided purely for completeness.
event.stopPropagation()
Returns an array containing the current EventTarget as the only entry or\nempty if the event is not being dispatched. This is not used in\nNode.js and is provided purely for completeness.
Sets the defaultPrevented property to true if cancelable is true.
defaultPrevented
Stops the invocation of event listeners after the current one completes.
Adds a new handler for the type event. Any given listener is added\nonly once per type and per capture option value.
capture
If the once option is true, the listener is removed after the\nnext time a type event is dispatched.
once
The capture option is not used by Node.js in any functional way other than\ntracking registered event listeners per the EventTarget specification.\nSpecifically, the capture option is used as part of the key when registering\na listener. Any individual listener may be added once with\ncapture = false, and once with capture = true.
capture = false
capture = true
function handler(event) {}\n\nconst target = new EventTarget();\ntarget.addEventListener('foo', handler, { capture: true }); // first\ntarget.addEventListener('foo', handler, { capture: false }); // second\n\n// Removes the second instance of handler\ntarget.removeEventListener('foo', handler);\n\n// Removes the first instance of handler\ntarget.removeEventListener('foo', handler, { capture: true });\n
Dispatches the event to the list of handlers for event.type.
event.type
The registered event listeners is synchronously invoked in the order they\nwere registered.
Removes the listener from the list of handlers for event type.
The CustomEvent object is an adaptation of the CustomEvent Web API.\nInstances are created internally by Node.js.
CustomEvent
Read-only.
The NodeEventTarget is a Node.js-specific extension to EventTarget\nthat emulates a subset of the EventEmitter API.
Node.js-specific extension to the EventTarget class that emulates the\nequivalent EventEmitter API. The only difference between addListener() and\naddEventListener() is that addListener() will return a reference to the\nEventTarget.
addListener()
addEventListener()
Node.js-specific extension to the EventTarget class that returns an array\nof event type names for which event listeners are registered.
Node.js-specific extension to the EventTarget class that returns the number\nof event listeners registered for the type.
Node.js-specific alias for eventTarget.removeListener().
eventTarget.removeListener()
Node.js-specific alias for eventTarget.addListener().
eventTarget.addListener()
Node.js-specific extension to the EventTarget class that adds a once\nlistener for the given event type. This is equivalent to calling on\nwith the once option set to true.
on
Node.js-specific extension to the EventTarget class. If type is specified,\nremoves all registered listeners for type, otherwise removes all registered\nlisteners.
Node.js-specific extension to the EventTarget class that removes the\nlistener for the given type. The only difference between removeListener()\nand removeEventListener() is that removeListener() will return a reference\nto the EventTarget.
removeListener()
removeEventListener()
The EventEmitter class is defined and exposed by the node:events module:
node:events
import { EventEmitter } from 'node:events';\n
const EventEmitter = require('node:events');\n
All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.
It supports the following option:
The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.
Listeners registered for the 'newListener' event are passed the event\nname and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname within the 'newListener' callback are inserted before the\nlistener that is in the process of being added.
name
class MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n if (event === 'event') {\n // Insert a new listener in front\n myEmitter.on('event', () => {\n console.log('B');\n });\n }\n});\nmyEmitter.on('event', () => {\n console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n// B\n// A\n
The 'removeListener' event is emitted after the listener is removed.
Alias for emitter.on(eventName, listener).
emitter.on(eventName, listener)
Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.
eventName
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n
const EventEmitter = require('node:events');\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n
Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array are strings or Symbols.
Symbol
import { EventEmitter } from 'node:events';\n\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n
const EventEmitter = require('node:events');\n\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n
Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nevents.defaultMaxListeners.
emitter.setMaxListeners(n)
events.defaultMaxListeners
Returns the number of listeners listening to the event named eventName.
Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n
Alias for emitter.removeListener().
emitter.removeListener()
Adds the listener function to the end of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\n
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The\nemitter.prependListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
emitter.prependListener()
const myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n
Adds a one-time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n
By default, event listeners are invoked in the order they are added. The\nemitter.prependOnceListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
emitter.prependOnceListener()
const myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n
Adds the listener function to the beginning of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.
server.prependListener('connection', (stream) => {\n console.log('someone connected!');\n});\n
Adds a one-time listener function for the event named eventName to the\nbeginning of the listeners array. The next time eventName is triggered, this\nlistener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,\nparticularly when the EventEmitter instance was created by some other\ncomponent or module (e.g. sockets or file streams).
Removes the specified listener from the listener array for the event named\neventName.
const callback = (stream) => {\n console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
removeListener() will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified eventName, then removeListener() must be\ncalled multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the\ntime of emitting are called in order. This implies that any\nremoveListener() or removeAllListeners() calls after emitting and\nbefore the last listener finishes execution will not remove them from\nemit() in progress. Subsequent events behave as expected.
removeAllListeners()
emit()
const myEmitter = new MyEmitter();\n\nconst callbackA = () => {\n console.log('A');\n myEmitter.removeListener('event', callbackB);\n};\n\nconst callbackB = () => {\n console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n// Prints:\n// A\n// B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n// Prints:\n// A\n
Because listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered after the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it means that any copies of the listener array as returned by\nthe emitter.listeners() method will need to be recreated.
emitter.listeners()
When a single function has been added as a handler multiple times for a single\nevent (as in the example below), removeListener() will remove the most\nrecently added instance. In the example the once('ping')\nlistener is removed:
once('ping')
const ee = new EventEmitter();\n\nfunction pong() {\n console.log('pong');\n}\n\nee.on('ping', pong);\nee.once('ping', pong);\nee.removeListener('ping', pong);\n\nee.emit('ping');\nee.emit('ping');\n
By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. The emitter.setMaxListeners() method allows the limit to be\nmodified for this specific EventEmitter instance. The value can be set to\nInfinity (or 0) to indicate an unlimited number of listeners.
10
emitter.setMaxListeners()
Infinity
0
Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).
.once()
const emitter = new EventEmitter();\nemitter.once('log', () => console.log('log once'));\n\n// Returns a new Array with a function `onceWrapper` which has a property\n// `listener` which contains the original listener bound above\nconst listeners = emitter.rawListeners('log');\nconst logFnWrapper = listeners[0];\n\n// Logs \"log once\" to the console and does not unbind the `once` event\nlogFnWrapper.listener();\n\n// Logs \"log once\" to the console and removes the listener\nlogFnWrapper();\n\nemitter.on('log', () => console.log('log persistently'));\n// Will return a new Array with a single function bound by `.on()` above\nconst newListeners = emitter.rawListeners('log');\n\n// Logs \"log persistently\" twice\nnewListeners[0]();\nemitter.emit('log');\n
err
...args
The Symbol.for('nodejs.rejection') method is called in case a\npromise rejection happens when emitting an event and\ncaptureRejections is enabled on the emitter.\nIt is possible to use events.captureRejectionSymbol in\nplace of Symbol.for('nodejs.rejection').
events.captureRejectionSymbol
import { EventEmitter, captureRejectionSymbol } from 'node:events';\n\nclass MyClass extends EventEmitter {\n constructor() {\n super({ captureRejections: true });\n }\n\n [captureRejectionSymbol](err, event, ...args) {\n console.log('rejection happened for', event, 'with', err, ...args);\n this.destroy(err);\n }\n\n destroy(err) {\n // Tear the resource down here.\n }\n}\n
const { EventEmitter, captureRejectionSymbol } = require('node:events');\n\nclass MyClass extends EventEmitter {\n constructor() {\n super({ captureRejections: true });\n }\n\n [captureRejectionSymbol](err, event, ...args) {\n console.log('rejection happened for', event, 'with', err, ...args);\n this.destroy(err);\n }\n\n destroy(err) {\n // Tear the resource down here.\n }\n}\n
Integrates EventEmitter with <AsyncResource> for EventEmitters that\nrequire manual async tracking. Specifically, all events emitted by instances\nof events.EventEmitterAsyncResource will run within its async context.
events.EventEmitterAsyncResource
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';\nimport { notStrictEqual, strictEqual } from 'node:assert';\nimport { executionAsyncId, triggerAsyncId } from 'node:async_hooks';\n\n// Async tracking tooling will identify this as 'Q'.\nconst ee1 = new EventEmitterAsyncResource({ name: 'Q' });\n\n// 'foo' listeners will run in the EventEmitters async context.\nee1.on('foo', () => {\n strictEqual(executionAsyncId(), ee1.asyncId);\n strictEqual(triggerAsyncId(), ee1.triggerAsyncId);\n});\n\nconst ee2 = new EventEmitter();\n\n// 'foo' listeners on ordinary EventEmitters that do not track async\n// context, however, run in the same async context as the emit().\nee2.on('foo', () => {\n notStrictEqual(executionAsyncId(), ee2.asyncId);\n notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);\n});\n\nPromise.resolve().then(() => {\n ee1.emit('foo');\n ee2.emit('foo');\n});\n
const { EventEmitterAsyncResource, EventEmitter } = require('node:events');\nconst { notStrictEqual, strictEqual } = require('node:assert');\nconst { executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\n// Async tracking tooling will identify this as 'Q'.\nconst ee1 = new EventEmitterAsyncResource({ name: 'Q' });\n\n// 'foo' listeners will run in the EventEmitters async context.\nee1.on('foo', () => {\n strictEqual(executionAsyncId(), ee1.asyncId);\n strictEqual(triggerAsyncId(), ee1.triggerAsyncId);\n});\n\nconst ee2 = new EventEmitter();\n\n// 'foo' listeners on ordinary EventEmitters that do not track async\n// context, however, run in the same async context as the emit().\nee2.on('foo', () => {\n notStrictEqual(executionAsyncId(), ee2.asyncId);\n notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);\n});\n\nPromise.resolve().then(() => {\n ee1.emit('foo');\n ee2.emit('foo');\n});\n
The EventEmitterAsyncResource class has the same methods and takes the\nsame options as EventEmitter and AsyncResource themselves.
EventEmitterAsyncResource
AsyncResource
The returned AsyncResource object has an additional eventEmitter property\nthat provides a reference to this EventEmitterAsyncResource.
eventEmitter
Call all destroy hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This must be manually called. If\nthe resource is left to be collected by the GC then the destroy hooks will\nnever be called.
destroy
By default, a maximum of 10 listeners can be registered for any single\nevent. This limit can be changed for individual EventEmitter instances\nusing the emitter.setMaxListeners(n) method. To change the default\nfor all EventEmitter instances, the events.defaultMaxListeners\nproperty can be used. If this value is not a positive number, a RangeError\nis thrown.
RangeError
Take caution when setting the events.defaultMaxListeners because the\nchange affects all EventEmitter instances, including those created before\nthe change is made. However, calling emitter.setMaxListeners(n) still has\nprecedence over events.defaultMaxListeners.
This is not a hard limit. The EventEmitter instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a \"possible EventEmitter memory leak\" has been detected. For any single\nEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()\nmethods can be used to temporarily avoid this warning:
emitter.getMaxListeners()
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n // do stuff\n emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
The --trace-warnings command-line flag can be used to display the\nstack trace for such warnings.
--trace-warnings
The emitted warning can be inspected with process.on('warning') and will\nhave the additional emitter, type, and count properties, referring to\nthe event emitter instance, the event's name and the number of attached\nlisteners, respectively.\nIts name property is set to 'MaxListenersExceededWarning'.
process.on('warning')
emitter
count
'MaxListenersExceededWarning'
This symbol shall be used to install a listener for only monitoring 'error'\nevents. Listeners installed using this symbol are called before the regular\n'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an\n'error' event is emitted. Therefore, the process will still crash if no\nregular 'error' listener is installed.
Value: <boolean>
Change the default captureRejections option on all new EventEmitter objects.
Value: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler.
For EventEmitters this behaves exactly the same as calling .listeners on\nthe emitter.
.listeners
For EventTargets this is the only way to get the event listeners for the\nevent target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';\n\n{\n const ee = new EventEmitter();\n const listener = () => console.log('Events are fun');\n ee.on('foo', listener);\n getEventListeners(ee, 'foo'); // [listener]\n}\n{\n const et = new EventTarget();\n const listener = () => console.log('Events are fun');\n et.addEventListener('foo', listener);\n getEventListeners(et, 'foo'); // [listener]\n}\n
const { getEventListeners, EventEmitter } = require('node:events');\n\n{\n const ee = new EventEmitter();\n const listener = () => console.log('Events are fun');\n ee.on('foo', listener);\n getEventListeners(ee, 'foo'); // [listener]\n}\n{\n const et = new EventTarget();\n const listener = () => console.log('Events are fun');\n et.addEventListener('foo', listener);\n getEventListeners(et, 'foo'); // [listener]\n}\n
Creates a Promise that is fulfilled when the EventEmitter emits the given\nevent or that is rejected if the EventEmitter emits 'error' while waiting.\nThe Promise will resolve with an array of all the arguments emitted to the\ngiven event.
This method is intentionally generic and works with the web platform\nEventTarget interface, which has no special\n'error' event semantics and does not listen to the 'error' event.
import { once, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ee = new EventEmitter();\n\nprocess.nextTick(() => {\n ee.emit('myevent', 42);\n});\n\nconst [value] = await once(ee, 'myevent');\nconsole.log(value);\n\nconst err = new Error('kaboom');\nprocess.nextTick(() => {\n ee.emit('error', err);\n});\n\ntry {\n await once(ee, 'myevent');\n} catch (err) {\n console.log('error happened', err);\n}\n
const { once, EventEmitter } = require('node:events');\n\nasync function run() {\n const ee = new EventEmitter();\n\n process.nextTick(() => {\n ee.emit('myevent', 42);\n });\n\n const [value] = await once(ee, 'myevent');\n console.log(value);\n\n const err = new Error('kaboom');\n process.nextTick(() => {\n ee.emit('error', err);\n });\n\n try {\n await once(ee, 'myevent');\n } catch (err) {\n console.log('error happened', err);\n }\n}\n\nrun();\n
The special handling of the 'error' event is only used when events.once()\nis used to wait for another event. If events.once() is used to wait for the\n'error' event itself, then it is treated as any other kind of event without\nspecial handling:
events.once()
error'
import { EventEmitter, once } from 'node:events';\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n .then(([err]) => console.log('ok', err.message))\n .catch((err) => console.log('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n
const { EventEmitter, once } = require('node:events');\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n .then(([err]) => console.log('ok', err.message))\n .catch((err) => console.log('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n
An <AbortSignal> can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';\n\nconst ee = new EventEmitter();\nconst ac = new AbortController();\n\nasync function foo(emitter, event, signal) {\n try {\n await once(emitter, event, { signal });\n console.log('event emitted!');\n } catch (error) {\n if (error.name === 'AbortError') {\n console.error('Waiting for the event was canceled!');\n } else {\n console.error('There was an error', error.message);\n }\n }\n}\n\nfoo(ee, 'foo', ac.signal);\nac.abort(); // Abort waiting for the event\nee.emit('foo'); // Prints: Waiting for the event was canceled!\n
const { EventEmitter, once } = require('node:events');\n\nconst ee = new EventEmitter();\nconst ac = new AbortController();\n\nasync function foo(emitter, event, signal) {\n try {\n await once(emitter, event, { signal });\n console.log('event emitted!');\n } catch (error) {\n if (error.name === 'AbortError') {\n console.error('Waiting for the event was canceled!');\n } else {\n console.error('There was an error', error.message);\n }\n }\n}\n\nfoo(ee, 'foo', ac.signal);\nac.abort(); // Abort waiting for the event\nee.emit('foo'); // Prints: Waiting for the event was canceled!\n
There is an edge case worth noting when using the events.once() function\nto await multiple events emitted on in the same batch of process.nextTick()\noperations, or whenever multiple events are emitted synchronously. Specifically,\nbecause the process.nextTick() queue is drained before the Promise microtask\nqueue, and because EventEmitter emits all events synchronously, it is possible\nfor events.once() to miss an event.
import { EventEmitter, once } from 'node:events';\nimport process from 'node:process';\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n await once(myEE, 'bar');\n console.log('bar');\n\n // This Promise will never resolve because the 'foo' event will\n // have already been emitted before the Promise is created.\n await once(myEE, 'foo');\n console.log('foo');\n}\n\nprocess.nextTick(() => {\n myEE.emit('bar');\n myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
const { EventEmitter, once } = require('node:events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n await once(myEE, 'bar');\n console.log('bar');\n\n // This Promise will never resolve because the 'foo' event will\n // have already been emitted before the Promise is created.\n await once(myEE, 'foo');\n console.log('foo');\n}\n\nprocess.nextTick(() => {\n myEE.emit('bar');\n myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
To catch both events, create each of the Promises before awaiting either\nof them, then it becomes possible to use Promise.all(), Promise.race(),\nor Promise.allSettled():
Promise.all()
Promise.race()
Promise.allSettled()
import { EventEmitter, once } from 'node:events';\nimport process from 'node:process';\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);\n console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('bar');\n myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
const { EventEmitter, once } = require('node:events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);\n console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('bar');\n myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.
import { EventEmitter, listenerCount } from 'node:events';\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(listenerCount(myEmitter, 'event'));\n// Prints: 2\n
const { EventEmitter, listenerCount } = require('node:events');\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(listenerCount(myEmitter, 'event'));\n// Prints: 2\n
import { on, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ee = new EventEmitter();\n\n// Emit later on\nprocess.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n});\n\nfor await (const event of on(ee, 'foo')) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n}\n// Unreachable here\n
const { on, EventEmitter } = require('node:events');\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo')) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n
Returns an AsyncIterator that iterates eventName events. It will throw\nif the EventEmitter emits 'error'. It removes all listeners when\nexiting the loop. The value returned by each iteration is an array\ncomposed of the emitted event arguments.
AsyncIterator
value
An <AbortSignal> can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ac = new AbortController();\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo', { signal: ac.signal })) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n\nprocess.nextTick(() => ac.abort());\n
const { on, EventEmitter } = require('node:events');\n\nconst ac = new AbortController();\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo', { signal: ac.signal })) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n\nprocess.nextTick(() => ac.abort());\n
import { setMaxListeners, EventEmitter } from 'node:events';\n\nconst target = new EventTarget();\nconst emitter = new EventEmitter();\n\nsetMaxListeners(5, target, emitter);\n
const {\n setMaxListeners,\n EventEmitter\n} = require('node:events');\n\nconst target = new EventTarget();\nconst emitter = new EventEmitter();\n\nsetMaxListeners(5, target, emitter);\n