Events#

Stability: 2 - Stable

Source Code:lib/events.js

Much of the Node.js core API is built around an idiomatic asynchronousevent-driven architecture in which certain kinds of objects (called "emitters")emit named events that causeFunction objects ("listeners") to be called.

For instance: anet.Server object emits an event each time a peerconnects to it; afs.ReadStream emits an event when the file is opened;astream emits an event whenever data is available to be read.

All objects that emit events are instances of theEventEmitter class. Theseobjects expose aneventEmitter.on() function that allows one or morefunctions to be attached to named events emitted by the object. Typically,event names are camel-cased strings but any valid JavaScript property keycan be used.

When theEventEmitter object emits an event, all of the functions attachedto that specific event are calledsynchronously. Any values returned by thecalled listeners areignored and discarded.

The following example shows a simpleEventEmitter instance with a singlelistener. TheeventEmitter.on() method is used to register listeners, whiletheeventEmitter.emit() method is used to trigger the event.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',() => {console.log('an event occurred!');});myEmitter.emit('event');constEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',() => {console.log('an event occurred!');});myEmitter.emit('event');

Passing arguments andthis to listeners#

TheeventEmitter.emit() method allows an arbitrary set of arguments to bepassed to the listener functions. Keep in mind that whenan ordinary listener function is called, the standardthis keywordis intentionally set to reference theEventEmitter instance to which thelistener is attached.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',function(a, b) {console.log(a, b,this,this === myEmitter);// Prints://   a b MyEmitter {//     _events: [Object: null prototype] { event: [Function (anonymous)] },//     _eventsCount: 1,//     _maxListeners: undefined,//     Symbol(shapeMode): false,//     Symbol(kCapture): false//   } true});myEmitter.emit('event','a','b');constEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',function(a, b) {console.log(a, b,this,this === myEmitter);// Prints://   a b MyEmitter {//     _events: [Object: null prototype] { event: [Function (anonymous)] },//     _eventsCount: 1,//     _maxListeners: undefined,//     Symbol(shapeMode): false,//     Symbol(kCapture): false//   } true});myEmitter.emit('event','a','b');

It is possible to use ES6 Arrow Functions as listeners, however, when doing so,thethis keyword will no longer reference theEventEmitter instance:

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',(a, b) => {console.log(a, b,this);// Prints: a b undefined});myEmitter.emit('event','a','b');constEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',(a, b) => {console.log(a, b,this);// Prints: a b {}});myEmitter.emit('event','a','b');

Asynchronous vs. synchronous#

TheEventEmitter calls all listeners synchronously in the order in whichthey were registered. This ensures the proper sequencing ofevents and helps avoid race conditions and logic errors. When appropriate,listener functions can switch to an asynchronous mode of operation usingthesetImmediate() orprocess.nextTick() methods:

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',(a, b) => {setImmediate(() => {console.log('this happens asynchronously');  });});myEmitter.emit('event','a','b');constEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('event',(a, b) => {setImmediate(() => {console.log('this happens asynchronously');  });});myEmitter.emit('event','a','b');

Handling events only once#

When a listener is registered using theeventEmitter.on() method, thatlistener is invokedevery time the named event is emitted.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();let m =0;myEmitter.on('event',() => {console.log(++m);});myEmitter.emit('event');// Prints: 1myEmitter.emit('event');// Prints: 2constEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();let m =0;myEmitter.on('event',() => {console.log(++m);});myEmitter.emit('event');// Prints: 1myEmitter.emit('event');// Prints: 2

Using theeventEmitter.once() method, it is possible to register a listenerthat is called at most once for a particular event. Once the event is emitted,the listener is unregistered andthen called.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();let m =0;myEmitter.once('event',() => {console.log(++m);});myEmitter.emit('event');// Prints: 1myEmitter.emit('event');// IgnoredconstEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();let m =0;myEmitter.once('event',() => {console.log(++m);});myEmitter.emit('event');// Prints: 1myEmitter.emit('event');// Ignored

Error events#

When an error occurs within anEventEmitter instance, the typical action isfor an'error' event to be emitted. These are treated as special caseswithin Node.js.

If anEventEmitter doesnot have at least one listener registered for the'error' event, and an'error' event is emitted, the error is thrown, astack trace is printed, and the Node.js process exits.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.emit('error',newError('whoops!'));// Throws and crashes Node.jsconstEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.emit('error',newError('whoops!'));// Throws and crashes Node.js

To guard against crashing the Node.js process thedomain module can beused. (Note, however, that thenode:domain module is deprecated.)

As a best practice, listeners should always be added for the'error' events.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('error',(err) => {console.error('whoops! there was an error');});myEmitter.emit('error',newError('whoops!'));// Prints: whoops! there was an errorconstEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();myEmitter.on('error',(err) => {console.error('whoops! there was an error');});myEmitter.emit('error',newError('whoops!'));// Prints: whoops! there was an error

It is possible to monitor'error' events without consuming the emitted errorby installing a listener using the symbolevents.errorMonitor.

import {EventEmitter, errorMonitor }from'node:events';const myEmitter =newEventEmitter();myEmitter.on(errorMonitor,(err) => {MyMonitoringTool.log(err);});myEmitter.emit('error',newError('whoops!'));// Still throws and crashes Node.jsconst {EventEmitter, errorMonitor } =require('node:events');const myEmitter =newEventEmitter();myEmitter.on(errorMonitor,(err) => {MyMonitoringTool.log(err);});myEmitter.emit('error',newError('whoops!'));// Still throws and crashes Node.js

Capture rejections of promises#

Usingasync functions with event handlers is problematic, because itcan lead to an unhandled rejection in case of a thrown exception:

import {EventEmitter }from'node:events';const ee =newEventEmitter();ee.on('something',async (value) => {thrownewError('kaboom');});constEventEmitter =require('node:events');const ee =newEventEmitter();ee.on('something',async (value) => {thrownewError('kaboom');});

ThecaptureRejections option in theEventEmitter constructor or the globalsetting change this behavior, installing a.then(undefined, handler)handler on thePromise. This handler routes the exceptionasynchronously to theSymbol.for('nodejs.rejection') methodif there is one, or to'error' event handler if there is none.

import {EventEmitter }from'node:events';const ee1 =newEventEmitter({captureRejections:true });ee1.on('something',async (value) => {thrownewError('kaboom');});ee1.on('error',console.log);const ee2 =newEventEmitter({captureRejections:true });ee2.on('something',async (value) => {thrownewError('kaboom');});ee2[Symbol.for('nodejs.rejection')] =console.log;constEventEmitter =require('node:events');const ee1 =newEventEmitter({captureRejections:true });ee1.on('something',async (value) => {thrownewError('kaboom');});ee1.on('error',console.log);const ee2 =newEventEmitter({captureRejections:true });ee2.on('something',async (value) => {thrownewError('kaboom');});ee2[Symbol.for('nodejs.rejection')] =console.log;

Settingevents.captureRejections = true will change the default for allnew instances ofEventEmitter.

import {EventEmitter }from'node:events';EventEmitter.captureRejections =true;const ee1 =newEventEmitter();ee1.on('something',async (value) => {thrownewError('kaboom');});ee1.on('error',console.log);const events =require('node:events');events.captureRejections =true;const ee1 =new events.EventEmitter();ee1.on('something',async (value) => {thrownewError('kaboom');});ee1.on('error',console.log);

The'error' events that are generated by thecaptureRejections behaviordo not have a catch handler to avoid infinite error loops: therecommendation is tonot useasync functions as'error' event handlers.

Class:EventEmitter#

History
VersionChanges
v13.4.0, v12.16.0

Added captureRejections option.

v0.1.26

Added in: v0.1.26

TheEventEmitter class is defined and exposed by thenode:events module:

import {EventEmitter }from'node:events';constEventEmitter =require('node:events');

AllEventEmitters emit the event'newListener' when new listeners areadded and'removeListener' when existing listeners are removed.

It supports the following option:

Event:'newListener'#

Added in: v0.1.26

TheEventEmitter instance will emit its own'newListener' eventbeforea listener is added to its internal array of listeners.

Listeners registered for the'newListener' event are passed the eventname and a reference to the listener being added.

The fact that the event is triggered before adding the listener has a subtlebut important side effect: anyadditional listeners registered to the samenamewithin the'newListener' callback are insertedbefore thelistener that is in the process of being added.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();// Only do this once so we don't loop forevermyEmitter.once('newListener',(event, listener) => {if (event ==='event') {// Insert a new listener in front    myEmitter.on('event',() => {console.log('B');    });  }});myEmitter.on('event',() => {console.log('A');});myEmitter.emit('event');// Prints://   B//   AconstEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();// Only do this once so we don't loop forevermyEmitter.once('newListener',(event, listener) => {if (event ==='event') {// Insert a new listener in front    myEmitter.on('event',() => {console.log('B');    });  }});myEmitter.on('event',() => {console.log('A');});myEmitter.emit('event');// Prints://   B//   A

Event:'removeListener'#

History
VersionChanges
v6.1.0, v4.7.0

For listeners attached using.once(), thelistener argument now yields the original listener function.

v0.9.3

Added in: v0.9.3

The'removeListener' event is emittedafter thelistener is removed.

emitter.addListener(eventName, listener)#

Added in: v0.1.26

Alias foremitter.on(eventName, listener).

emitter.emit(eventName[, ...args])#

Added in: v0.1.26

Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied argumentsto each.

Returnstrue if the event had listeners,false otherwise.

import {EventEmitter }from'node:events';const myEmitter =newEventEmitter();// First listenermyEmitter.on('event',functionfirstListener() {console.log('Helloooo! first listener');});// Second listenermyEmitter.on('event',functionsecondListener(arg1, arg2) {console.log(`event with parameters${arg1},${arg2} in second listener`);});// Third listenermyEmitter.on('event',functionthirdListener(...args) {const parameters = args.join(', ');console.log(`event with parameters${parameters} in third listener`);});console.log(myEmitter.listeners('event'));myEmitter.emit('event',1,2,3,4,5);// Prints:// [//   [Function: firstListener],//   [Function: secondListener],//   [Function: thirdListener]// ]// Helloooo! first listener// event with parameters 1, 2 in second listener// event with parameters 1, 2, 3, 4, 5 in third listenerconstEventEmitter =require('node:events');const myEmitter =newEventEmitter();// First listenermyEmitter.on('event',functionfirstListener() {console.log('Helloooo! first listener');});// Second listenermyEmitter.on('event',functionsecondListener(arg1, arg2) {console.log(`event with parameters${arg1},${arg2} in second listener`);});// Third listenermyEmitter.on('event',functionthirdListener(...args) {const parameters = args.join(', ');console.log(`event with parameters${parameters} in third listener`);});console.log(myEmitter.listeners('event'));myEmitter.emit('event',1,2,3,4,5);// Prints:// [//   [Function: firstListener],//   [Function: secondListener],//   [Function: thirdListener]// ]// Helloooo! first listener// event with parameters 1, 2 in second listener// event with parameters 1, 2, 3, 4, 5 in third listener

emitter.eventNames()#

Added in: v6.0.0

Returns an array listing the events for which the emitter has registeredlisteners.

import {EventEmitter }from'node:events';const myEE =newEventEmitter();myEE.on('foo',() => {});myEE.on('bar',() => {});const sym =Symbol('symbol');myEE.on(sym,() => {});console.log(myEE.eventNames());// Prints: [ 'foo', 'bar', Symbol(symbol) ]constEventEmitter =require('node:events');const myEE =newEventEmitter();myEE.on('foo',() => {});myEE.on('bar',() => {});const sym =Symbol('symbol');myEE.on(sym,() => {});console.log(myEE.eventNames());// Prints: [ 'foo', 'bar', Symbol(symbol) ]

emitter.getMaxListeners()#

Added in: v1.0.0

Returns the current max listener value for theEventEmitter which is eitherset byemitter.setMaxListeners(n) or defaults toevents.defaultMaxListeners.

emitter.listenerCount(eventName[, listener])#

History
VersionChanges
v19.8.0, v18.16.0

Added thelistener argument.

v3.2.0

Added in: v3.2.0

Returns the number of listeners listening for the event namedeventName.Iflistener is provided, it will return how many times the listener is foundin the list of the listeners of the event.

emitter.listeners(eventName)#

History
VersionChanges
v7.0.0

For listeners attached using.once() this returns the original listeners instead of wrapper functions now.

v0.1.26

Added in: v0.1.26

Returns a copy of the array of listeners for the event namedeventName.

server.on('connection',(stream) => {console.log('someone connected!');});console.log(util.inspect(server.listeners('connection')));// Prints: [ [Function] ]

emitter.off(eventName, listener)#

Added in: v10.0.0

Alias foremitter.removeListener().

emitter.on(eventName, listener)#

Added in: v0.1.101

Adds thelistener function to the end of the listeners array for theevent namedeventName. No checks are made to see if thelistener hasalready been added. Multiple calls passing the same combination ofeventNameandlistener will result in thelistener being added, and called, multipletimes.

server.on('connection',(stream) => {console.log('someone connected!');});

Returns a reference to theEventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add theevent listener to the beginning of the listeners array.

import {EventEmitter }from'node:events';const myEE =newEventEmitter();myEE.on('foo',() =>console.log('a'));myEE.prependListener('foo',() =>console.log('b'));myEE.emit('foo');// Prints://   b//   aconstEventEmitter =require('node:events');const myEE =newEventEmitter();myEE.on('foo',() =>console.log('a'));myEE.prependListener('foo',() =>console.log('b'));myEE.emit('foo');// Prints://   b//   a

emitter.once(eventName, listener)#

Added in: v0.3.0

Adds aone-timelistener function for the event namedeventName. Thenext timeeventName is triggered, this listener is removed and then invoked.

server.once('connection',(stream) => {console.log('Ah, we have our first user!');});

Returns a reference to theEventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add theevent listener to the beginning of the listeners array.

import {EventEmitter }from'node:events';const myEE =newEventEmitter();myEE.once('foo',() =>console.log('a'));myEE.prependOnceListener('foo',() =>console.log('b'));myEE.emit('foo');// Prints://   b//   aconstEventEmitter =require('node:events');const myEE =newEventEmitter();myEE.once('foo',() =>console.log('a'));myEE.prependOnceListener('foo',() =>console.log('b'));myEE.emit('foo');// Prints://   b//   a

emitter.prependListener(eventName, listener)#

Added in: v6.0.0

Adds thelistener function to thebeginning of the listeners array for theevent namedeventName. No checks are made to see if thelistener hasalready been added. Multiple calls passing the same combination ofeventNameandlistener will result in thelistener being added, and called, multipletimes.

server.prependListener('connection',(stream) => {console.log('someone connected!');});

Returns a reference to theEventEmitter, so that calls can be chained.

emitter.prependOnceListener(eventName, listener)#

Added in: v6.0.0

Adds aone-timelistener function for the event namedeventName to thebeginning of the listeners array. The next timeeventName is triggered, thislistener is removed, and then invoked.

server.prependOnceListener('connection',(stream) => {console.log('Ah, we have our first user!');});

Returns a reference to theEventEmitter, so that calls can be chained.

emitter.removeAllListeners([eventName])#

Added in: v0.1.26

Removes all listeners, or those of the specifiedeventName.

It is bad practice to remove listeners added elsewhere in the code,particularly when theEventEmitter instance was created by some othercomponent or module (e.g. sockets or file streams).

Returns a reference to theEventEmitter, so that calls can be chained.

emitter.removeListener(eventName, listener)#

Added in: v0.1.26

Removes the specifiedlistener from the listener array for the event namedeventName.

constcallback = (stream) => {console.log('someone connected!');};server.on('connection', callback);// ...server.removeListener('connection', callback);

removeListener() will remove, at most, one instance of a listener from thelistener array. If any single listener has been added multiple times to thelistener array for the specifiedeventName, thenremoveListener() must becalled multiple times to remove each instance.

Once an event is emitted, all listeners attached to it at thetime of emitting are called in order. This implies that anyremoveListener() orremoveAllListeners() callsafter emitting andbefore the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

import {EventEmitter }from'node:events';classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();constcallbackA = () => {console.log('A');  myEmitter.removeListener('event', callbackB);};constcallbackB = () => {console.log('B');};myEmitter.on('event', callbackA);myEmitter.on('event', callbackB);// callbackA removes listener callbackB but it will still be called.// Internal listener array at time of emit [callbackA, callbackB]myEmitter.emit('event');// Prints://   A//   B// callbackB is now removed.// Internal listener array [callbackA]myEmitter.emit('event');// Prints://   AconstEventEmitter =require('node:events');classMyEmitterextendsEventEmitter {}const myEmitter =newMyEmitter();constcallbackA = () => {console.log('A');  myEmitter.removeListener('event', callbackB);};constcallbackB = () => {console.log('B');};myEmitter.on('event', callbackA);myEmitter.on('event', callbackB);// callbackA removes listener callbackB but it will still be called.// Internal listener array at time of emit [callbackA, callbackB]myEmitter.emit('event');// Prints://   A//   B// callbackB is now removed.// Internal listener array [callbackA]myEmitter.emit('event');// Prints://   A

Because listeners are managed using an internal array, calling this willchange the position indexes of any listener registeredafter the listenerbeing removed. This will not impact the order in which listeners are called,but it means that any copies of the listener array as returned bytheemitter.listeners() method will need to be recreated.

When a single function has been added as a handler multiple times for a singleevent (as in the example below),removeListener() will remove the mostrecently added instance. In the example theonce('ping')listener is removed:

import {EventEmitter }from'node:events';const ee =newEventEmitter();functionpong() {console.log('pong');}ee.on('ping', pong);ee.once('ping', pong);ee.removeListener('ping', pong);ee.emit('ping');ee.emit('ping');constEventEmitter =require('node:events');const ee =newEventEmitter();functionpong() {console.log('pong');}ee.on('ping', pong);ee.once('ping', pong);ee.removeListener('ping', pong);ee.emit('ping');ee.emit('ping');

Returns a reference to theEventEmitter, so that calls can be chained.

emitter.setMaxListeners(n)#

Added in: v0.3.5

By defaultEventEmitters will print a warning if more than10 listeners areadded for a particular event. This is a useful default that helps findingmemory leaks. Theemitter.setMaxListeners() method allows the limit to bemodified for this specificEventEmitter instance. The value can be set toInfinity (or0) to indicate an unlimited number of listeners.

Returns a reference to theEventEmitter, so that calls can be chained.

emitter.rawListeners(eventName)#

Added in: v9.4.0

Returns a copy of the array of listeners for the event namedeventName,including any wrappers (such as those created by.once()).

import {EventEmitter }from'node:events';const emitter =newEventEmitter();emitter.once('log',() =>console.log('log once'));// Returns a new Array with a function `onceWrapper` which has a property// `listener` which contains the original listener bound aboveconst listeners = emitter.rawListeners('log');const logFnWrapper = listeners[0];// Logs "log once" to the console and does not unbind the `once` eventlogFnWrapper.listener();// Logs "log once" to the console and removes the listenerlogFnWrapper();emitter.on('log',() =>console.log('log persistently'));// Will return a new Array with a single function bound by `.on()` aboveconst newListeners = emitter.rawListeners('log');// Logs "log persistently" twicenewListeners[0]();emitter.emit('log');constEventEmitter =require('node:events');const emitter =newEventEmitter();emitter.once('log',() =>console.log('log once'));// Returns a new Array with a function `onceWrapper` which has a property// `listener` which contains the original listener bound aboveconst listeners = emitter.rawListeners('log');const logFnWrapper = listeners[0];// Logs "log once" to the console and does not unbind the `once` eventlogFnWrapper.listener();// Logs "log once" to the console and removes the listenerlogFnWrapper();emitter.on('log',() =>console.log('log persistently'));// Will return a new Array with a single function bound by `.on()` aboveconst newListeners = emitter.rawListeners('log');// Logs "log persistently" twicenewListeners[0]();emitter.emit('log');

emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])#

History
VersionChanges
v17.4.0, v16.14.0

No longer experimental.

v13.4.0, v12.16.0

Added in: v13.4.0, v12.16.0

TheSymbol.for('nodejs.rejection') method is called in case apromise rejection happens when emitting an event andcaptureRejections is enabled on the emitter.It is possible to useevents.captureRejectionSymbol inplace ofSymbol.for('nodejs.rejection').

import {EventEmitter, captureRejectionSymbol }from'node:events';classMyClassextendsEventEmitter {constructor() {super({captureRejections:true });  }  [captureRejectionSymbol](err, event, ...args) {console.log('rejection happened for', event,'with', err, ...args);this.destroy(err);  }destroy(err) {// Tear the resource down here.  }}const {EventEmitter, captureRejectionSymbol } =require('node:events');classMyClassextendsEventEmitter {constructor() {super({captureRejections:true });  }  [captureRejectionSymbol](err, event, ...args) {console.log('rejection happened for', event,'with', err, ...args);this.destroy(err);  }destroy(err) {// Tear the resource down here.  }}

events.defaultMaxListeners#

Added in: v0.11.2

By default, a maximum of10 listeners can be registered for any singleevent. This limit can be changed for individualEventEmitter instancesusing theemitter.setMaxListeners(n) method. To change the defaultforallEventEmitter instances, theevents.defaultMaxListenersproperty can be used. If this value is not a positive number, aRangeErroris thrown.

Take caution when setting theevents.defaultMaxListeners because thechange affectsallEventEmitter instances, including those created beforethe change is made. However, callingemitter.setMaxListeners(n) still hasprecedence overevents.defaultMaxListeners.

This is not a hard limit. TheEventEmitter instance will allowmore listeners to be added but will output a trace warning to stderr indicatingthat a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter, theemitter.getMaxListeners() andemitter.setMaxListeners()methods can be used to temporarily avoid this warning:

defaultMaxListeners has no effect onAbortSignal instances. While it isstill possible to useemitter.setMaxListeners(n) to set a warning limitfor individualAbortSignal instances, per defaultAbortSignal instances will not warn.

import {EventEmitter }from'node:events';const emitter =newEventEmitter();emitter.setMaxListeners(emitter.getMaxListeners() +1);emitter.once('event',() => {// do stuff  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() -1,0));});constEventEmitter =require('node:events');const emitter =newEventEmitter();emitter.setMaxListeners(emitter.getMaxListeners() +1);emitter.once('event',() => {// do stuff  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() -1,0));});

The--trace-warnings command-line flag can be used to display thestack trace for such warnings.

The emitted warning can be inspected withprocess.on('warning') and willhave the additionalemitter,type, andcount properties, referring tothe event emitter instance, the event's name and the number of attachedlisteners, respectively.Itsname property is set to'MaxListenersExceededWarning'.

events.errorMonitor#

Added in: v13.6.0, v12.17.0

This symbol shall be used to install a listener for only monitoring'error'events. Listeners installed using this symbol are called before the regular'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an'error' event is emitted. Therefore, the process will still crash if noregular'error' listener is installed.

events.getEventListeners(emitterOrTarget, eventName)#

Added in: v15.2.0, v14.17.0

Returns a copy of the array of listeners for the event namedeventName.

ForEventEmitters this behaves exactly the same as calling.listeners onthe emitter.

ForEventTargets this is the only way to get the event listeners for theevent target. This is useful for debugging and diagnostic purposes.

import { getEventListeners,EventEmitter }from'node:events';{const ee =newEventEmitter();constlistener = () =>console.log('Events are fun');  ee.on('foo', listener);console.log(getEventListeners(ee,'foo'));// [ [Function: listener] ]}{const et =newEventTarget();constlistener = () =>console.log('Events are fun');  et.addEventListener('foo', listener);console.log(getEventListeners(et,'foo'));// [ [Function: listener] ]}const { getEventListeners,EventEmitter } =require('node:events');{const ee =newEventEmitter();constlistener = () =>console.log('Events are fun');  ee.on('foo', listener);console.log(getEventListeners(ee,'foo'));// [ [Function: listener] ]}{const et =newEventTarget();constlistener = () =>console.log('Events are fun');  et.addEventListener('foo', listener);console.log(getEventListeners(et,'foo'));// [ [Function: listener] ]}

events.getMaxListeners(emitterOrTarget)#

Added in: v19.9.0, v18.17.0

Returns the currently set max amount of listeners.

ForEventEmitters this behaves exactly the same as calling.getMaxListeners onthe emitter.

ForEventTargets this is the only way to get the max event listeners for theevent target. If the number of event handlers on a single EventTarget exceedsthe max set, the EventTarget will print a warning.

import { getMaxListeners, setMaxListeners,EventEmitter }from'node:events';{const ee =newEventEmitter();console.log(getMaxListeners(ee));// 10setMaxListeners(11, ee);console.log(getMaxListeners(ee));// 11}{const et =newEventTarget();console.log(getMaxListeners(et));// 10setMaxListeners(11, et);console.log(getMaxListeners(et));// 11}const { getMaxListeners, setMaxListeners,EventEmitter } =require('node:events');{const ee =newEventEmitter();console.log(getMaxListeners(ee));// 10setMaxListeners(11, ee);console.log(getMaxListeners(ee));// 11}{const et =newEventTarget();console.log(getMaxListeners(et));// 10setMaxListeners(11, et);console.log(getMaxListeners(et));// 11}

events.once(emitter, name[, options])#

History
VersionChanges
v15.0.0

Thesignal option is supported now.

v11.13.0, v10.16.0

Added in: v11.13.0, v10.16.0

Creates aPromise that is fulfilled when theEventEmitter emits the givenevent or that is rejected if theEventEmitter emits'error' while waiting.ThePromise will resolve with an array of all the arguments emitted to thegiven event.

This method is intentionally generic and works with the web platformEventTarget interface, which has no special'error' event semantics and does not listen to the'error' event.

import { once,EventEmitter }from'node:events';import processfrom'node:process';const ee =newEventEmitter();process.nextTick(() => {  ee.emit('myevent',42);});const [value] =awaitonce(ee,'myevent');console.log(value);const err =newError('kaboom');process.nextTick(() => {  ee.emit('error', err);});try {awaitonce(ee,'myevent');}catch (err) {console.error('error happened', err);}const { once,EventEmitter } =require('node:events');asyncfunctionrun() {const ee =newEventEmitter();  process.nextTick(() => {    ee.emit('myevent',42);  });const [value] =awaitonce(ee,'myevent');console.log(value);const err =newError('kaboom');  process.nextTick(() => {    ee.emit('error', err);  });try {awaitonce(ee,'myevent');  }catch (err) {console.error('error happened', err);  }}run();

The special handling of the'error' event is only used whenevents.once()is used to wait for another event. Ifevents.once() is used to wait for the'error' event itself, then it is treated as any other kind of event withoutspecial handling:

import {EventEmitter, once }from'node:events';const ee =newEventEmitter();once(ee,'error')  .then(([err]) =>console.log('ok', err.message))  .catch((err) =>console.error('error', err.message));ee.emit('error',newError('boom'));// Prints: ok boomconst {EventEmitter, once } =require('node:events');const ee =newEventEmitter();once(ee,'error')  .then(([err]) =>console.log('ok', err.message))  .catch((err) =>console.error('error', err.message));ee.emit('error',newError('boom'));// Prints: ok boom

An<AbortSignal> can be used to cancel waiting for the event:

import {EventEmitter, once }from'node:events';const ee =newEventEmitter();const ac =newAbortController();asyncfunctionfoo(emitter, event, signal) {try {awaitonce(emitter, event, { signal });console.log('event emitted!');  }catch (error) {if (error.name ==='AbortError') {console.error('Waiting for the event was canceled!');    }else {console.error('There was an error', error.message);    }  }}foo(ee,'foo', ac.signal);ac.abort();// Prints: Waiting for the event was canceled!const {EventEmitter, once } =require('node:events');const ee =newEventEmitter();const ac =newAbortController();asyncfunctionfoo(emitter, event, signal) {try {awaitonce(emitter, event, { signal });console.log('event emitted!');  }catch (error) {if (error.name ==='AbortError') {console.error('Waiting for the event was canceled!');    }else {console.error('There was an error', error.message);    }  }}foo(ee,'foo', ac.signal);ac.abort();// Prints: Waiting for the event was canceled!

Awaiting multiple events emitted onprocess.nextTick()#

There is an edge case worth noting when using theevents.once() functionto await multiple events emitted on in the same batch ofprocess.nextTick()operations, or whenever multiple events are emitted synchronously. Specifically,because theprocess.nextTick() queue is drained before thePromise microtaskqueue, and becauseEventEmitter emits all events synchronously, it is possibleforevents.once() to miss an event.

import {EventEmitter, once }from'node:events';import processfrom'node:process';const myEE =newEventEmitter();asyncfunctionfoo() {awaitonce(myEE,'bar');console.log('bar');// This Promise will never resolve because the 'foo' event will// have already been emitted before the Promise is created.awaitonce(myEE,'foo');console.log('foo');}process.nextTick(() => {  myEE.emit('bar');  myEE.emit('foo');});foo().then(() =>console.log('done'));const {EventEmitter, once } =require('node:events');const myEE =newEventEmitter();asyncfunctionfoo() {awaitonce(myEE,'bar');console.log('bar');// This Promise will never resolve because the 'foo' event will// have already been emitted before the Promise is created.awaitonce(myEE,'foo');console.log('foo');}process.nextTick(() => {  myEE.emit('bar');  myEE.emit('foo');});foo().then(() =>console.log('done'));

To catch both events, create each of the Promisesbefore awaiting eitherof them, then it becomes possible to usePromise.all(),Promise.race(),orPromise.allSettled():

import {EventEmitter, once }from'node:events';import processfrom'node:process';const myEE =newEventEmitter();asyncfunctionfoo() {awaitPromise.all([once(myEE,'bar'),once(myEE,'foo')]);console.log('foo','bar');}process.nextTick(() => {  myEE.emit('bar');  myEE.emit('foo');});foo().then(() =>console.log('done'));const {EventEmitter, once } =require('node:events');const myEE =newEventEmitter();asyncfunctionfoo() {awaitPromise.all([once(myEE,'bar'),once(myEE,'foo')]);console.log('foo','bar');}process.nextTick(() => {  myEE.emit('bar');  myEE.emit('foo');});foo().then(() =>console.log('done'));

events.captureRejections#

History
VersionChanges
v17.4.0, v16.14.0

No longer experimental.

v13.4.0, v12.16.0

Added in: v13.4.0, v12.16.0

Change the defaultcaptureRejections option on all newEventEmitter objects.

events.captureRejectionSymbol#

History
VersionChanges
v17.4.0, v16.14.0

No longer experimental.

v13.4.0, v12.16.0

Added in: v13.4.0, v12.16.0

  • Type:<symbol>Symbol.for('nodejs.rejection')

See how to write a customrejection handler.

events.listenerCount(emitterOrTarget, eventName)#

History
VersionChanges
v25.4.0

Now accepts EventTarget arguments.

v25.4.0

Deprecation revoked.

v3.2.0

Documentation-only deprecation.

v0.9.12

Added in: v0.9.12

Returns the number of registered listeners for the event namedeventName.

ForEventEmitters this behaves exactly the same as calling.listenerCounton the emitter.

ForEventTargets this is the only way to obtain the listener count. This canbe useful for debugging and diagnostic purposes.

import {EventEmitter, listenerCount }from'node:events';{const ee =newEventEmitter();  ee.on('event',() => {});  ee.on('event',() => {});console.log(listenerCount(ee,'event'));// 2}{const et =newEventTarget();  et.addEventListener('event',() => {});  et.addEventListener('event',() => {});console.log(listenerCount(et,'event'));// 2}const {EventEmitter, listenerCount } =require('node:events');{const ee =newEventEmitter();  ee.on('event',() => {});  ee.on('event',() => {});console.log(listenerCount(ee,'event'));// 2}{const et =newEventTarget();  et.addEventListener('event',() => {});  et.addEventListener('event',() => {});console.log(listenerCount(et,'event'));// 2}

events.on(emitter, eventName[, options])#

History
VersionChanges
v22.0.0, v20.13.0

SupporthighWaterMark andlowWaterMark options, For consistency. Old options are still supported.

v20.0.0

Theclose,highWatermark, andlowWatermark options are supported now.

v13.6.0, v12.16.0

Added in: v13.6.0, v12.16.0

  • emitter<EventEmitter>
  • eventName<string> |<symbol> The name of the event being listened for
  • options<Object>
    • signal<AbortSignal> Can be used to cancel awaiting events.
    • close<string[]> Names of events that will end the iteration.
    • highWaterMark<integer>Default:Number.MAX_SAFE_INTEGERThe high watermark. The emitter is paused every time the size of eventsbeing buffered is higher than it. Supported only on emitters implementingpause() andresume() methods.
    • lowWaterMark<integer>Default:1The low watermark. The emitter is resumed every time the size of eventsbeing buffered is lower than it. Supported only on emitters implementingpause() andresume() methods.
  • Returns:<AsyncIterator> that iterateseventName events emitted by theemitter
import { on,EventEmitter }from'node:events';import processfrom'node:process';const ee =newEventEmitter();// Emit later onprocess.nextTick(() => {  ee.emit('foo','bar');  ee.emit('foo',42);});forawait (const eventofon(ee,'foo')) {// The execution of this inner block is synchronous and it// processes one event at a time (even with await). Do not use// if concurrent execution is required.console.log(event);// prints ['bar'] [42]}// Unreachable hereconst { on,EventEmitter } =require('node:events');(async () => {const ee =newEventEmitter();// Emit later on  process.nextTick(() => {    ee.emit('foo','bar');    ee.emit('foo',42);  });forawait (const eventofon(ee,'foo')) {// The execution of this inner block is synchronous and it// processes one event at a time (even with await). Do not use// if concurrent execution is required.console.log(event);// prints ['bar'] [42]  }// Unreachable here})();

Returns anAsyncIterator that iterateseventName events. It will throwif theEventEmitter emits'error'. It removes all listeners whenexiting the loop. Thevalue returned by each iteration is an arraycomposed of the emitted event arguments.

An<AbortSignal> can be used to cancel waiting on events:

import { on,EventEmitter }from'node:events';import processfrom'node:process';const ac =newAbortController();(async () => {const ee =newEventEmitter();// Emit later on  process.nextTick(() => {    ee.emit('foo','bar');    ee.emit('foo',42);  });forawait (const eventofon(ee,'foo', {signal: ac.signal })) {// The execution of this inner block is synchronous and it// processes one event at a time (even with await). Do not use// if concurrent execution is required.console.log(event);// prints ['bar'] [42]  }// Unreachable here})();process.nextTick(() => ac.abort());const { on,EventEmitter } =require('node:events');const ac =newAbortController();(async () => {const ee =newEventEmitter();// Emit later on  process.nextTick(() => {    ee.emit('foo','bar');    ee.emit('foo',42);  });forawait (const eventofon(ee,'foo', {signal: ac.signal })) {// The execution of this inner block is synchronous and it// processes one event at a time (even with await). Do not use// if concurrent execution is required.console.log(event);// prints ['bar'] [42]  }// Unreachable here})();process.nextTick(() => ac.abort());

events.setMaxListeners(n[, ...eventTargets])#

Added in: v15.4.0
import { setMaxListeners,EventEmitter }from'node:events';const target =newEventTarget();const emitter =newEventEmitter();setMaxListeners(5, target, emitter);const {  setMaxListeners,EventEmitter,} =require('node:events');const target =newEventTarget();const emitter =newEventEmitter();setMaxListeners(5, target, emitter);

events.addAbortListener(signal, listener)#

History
VersionChanges
v24.0.0, v22.16.0

Change stability index for this feature from Experimental to Stable.

v20.5.0, v18.18.0

Added in: v20.5.0, v18.18.0

Listens once to theabort event on the providedsignal.

Listening to theabort event on abort signals is unsafe and maylead to resource leaks since another third party with the signal cancalle.stopImmediatePropagation(). Unfortunately Node.js cannot changethis since it would violate the web standard. Additionally, the originalAPI makes it easy to forget to remove listeners.

This API allows safely usingAbortSignals in Node.js APIs by solving thesetwo issues by listening to the event such thatstopImmediatePropagation doesnot prevent the listener from running.

Returns a disposable so that it may be unsubscribed from more easily.

const { addAbortListener } =require('node:events');functionexample(signal) {let disposable;try {    signal.addEventListener('abort',(e) => e.stopImmediatePropagation());    disposable =addAbortListener(signal,(e) => {// Do something when signal is aborted.    });  }finally {    disposable?.[Symbol.dispose]();  }}import { addAbortListener }from'node:events';functionexample(signal) {let disposable;try {    signal.addEventListener('abort',(e) => e.stopImmediatePropagation());    disposable =addAbortListener(signal,(e) => {// Do something when signal is aborted.    });  }finally {    disposable?.[Symbol.dispose]();  }}

Class:events.EventEmitterAsyncResource extends EventEmitter#

Added in: v17.4.0, v16.14.0

IntegratesEventEmitter with<AsyncResource> forEventEmitters thatrequire manual async tracking. Specifically, all events emitted by instancesofevents.EventEmitterAsyncResource will run within itsasync context.

import {EventEmitterAsyncResource,EventEmitter }from'node:events';import { notStrictEqual, strictEqual }from'node:assert';import { executionAsyncId, triggerAsyncId }from'node:async_hooks';// Async tracking tooling will identify this as 'Q'.const ee1 =newEventEmitterAsyncResource({name:'Q' });// 'foo' listeners will run in the EventEmitters async context.ee1.on('foo',() => {strictEqual(executionAsyncId(), ee1.asyncId);strictEqual(triggerAsyncId(), ee1.triggerAsyncId);});const ee2 =newEventEmitter();// 'foo' listeners on ordinary EventEmitters that do not track async// context, however, run in the same async context as the emit().ee2.on('foo',() => {notStrictEqual(executionAsyncId(), ee2.asyncId);notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);});Promise.resolve().then(() => {  ee1.emit('foo');  ee2.emit('foo');});const {EventEmitterAsyncResource,EventEmitter } =require('node:events');const { notStrictEqual, strictEqual } =require('node:assert');const { executionAsyncId, triggerAsyncId } =require('node:async_hooks');// Async tracking tooling will identify this as 'Q'.const ee1 =newEventEmitterAsyncResource({name:'Q' });// 'foo' listeners will run in the EventEmitters async context.ee1.on('foo',() => {strictEqual(executionAsyncId(), ee1.asyncId);strictEqual(triggerAsyncId(), ee1.triggerAsyncId);});const ee2 =newEventEmitter();// 'foo' listeners on ordinary EventEmitters that do not track async// context, however, run in the same async context as the emit().ee2.on('foo',() => {notStrictEqual(executionAsyncId(), ee2.asyncId);notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);});Promise.resolve().then(() => {  ee1.emit('foo');  ee2.emit('foo');});

TheEventEmitterAsyncResource class has the same methods and takes thesame options asEventEmitter andAsyncResource themselves.

new events.EventEmitterAsyncResource([options])#

  • options<Object>
    • captureRejections<boolean> It enablesautomatic capturing of promise rejection.Default:false.
    • name<string> The type of async event.Default:new.target.name.
    • triggerAsyncId<number> The ID of the execution context that created thisasync event.Default:executionAsyncId().
    • requireManualDestroy<boolean> If set totrue, disablesemitDestroywhen the object is garbage collected. This usually does not need to be set(even ifemitDestroy is called manually), unless the resource'sasyncIdis retrieved and the sensitive API'semitDestroy is called with it.When set tofalse, theemitDestroy call on garbage collectionwill only take place if there is at least one activedestroy hook.Default:false.

eventemitterasyncresource.asyncId#

  • Type:<number> The uniqueasyncId assigned to the resource.

eventemitterasyncresource.asyncResource#

The returnedAsyncResource object has an additionaleventEmitter propertythat provides a reference to thisEventEmitterAsyncResource.

eventemitterasyncresource.emitDestroy()#

Call alldestroy hooks. This should only ever be called once. An error willbe thrown if it is called more than once. Thismust be manually called. Ifthe resource is left to be collected by the GC then thedestroy hooks willnever be called.

eventemitterasyncresource.triggerAsyncId#

  • Type:<number> The sametriggerAsyncId that is passed to theAsyncResource constructor.

EventTarget andEvent API#

History
VersionChanges
v16.0.0

changed EventTarget error handling.

v15.4.0

No longer experimental.

v15.0.0

TheEventTarget andEvent classes are now available as globals.

v14.5.0

Added in: v14.5.0

TheEventTarget andEvent objects are a Node.js-specific implementationof theEventTarget Web API that are exposed by some Node.js core APIs.

const target =newEventTarget();target.addEventListener('foo',(event) => {console.log('foo event happened!');});

Node.jsEventTarget vs. DOMEventTarget#

There are two key differences between the Node.jsEventTarget and theEventTarget Web API:

  1. Whereas DOMEventTarget instancesmay be hierarchical, there is noconcept of hierarchy and event propagation in Node.js. That is, an eventdispatched to anEventTarget does not propagate through a hierarchy ofnested target objects that may each have their own set of handlers for theevent.
  2. In the Node.jsEventTarget, if an event listener is an async functionor returns aPromise, and the returnedPromise rejects, the rejectionis automatically captured and handled the same way as a listener thatthrows synchronously (seeEventTarget error handling for details).

NodeEventTarget vs.EventEmitter#

TheNodeEventTarget object implements a modified subset of theEventEmitter API that allows it to closelyemulate anEventEmitter incertain situations. ANodeEventTarget isnot an instance ofEventEmitterand cannot be used in place of anEventEmitter in most cases.

  1. UnlikeEventEmitter, any givenlistener can be registered at most onceper eventtype. Attempts to register alistener multiple times areignored.
  2. TheNodeEventTarget does not emulate the fullEventEmitter API.Specifically theprependListener(),prependOnceListener(),rawListeners(), anderrorMonitor APIs are not emulated.The'newListener' and'removeListener' events will also not be emitted.
  3. TheNodeEventTarget does not implement any special default behaviorfor events with type'error'.
  4. TheNodeEventTarget supportsEventListener objects as well asfunctions as handlers for all event types.

Event listener#

Event listeners registered for an eventtype may either be JavaScriptfunctions or objects with ahandleEvent property whose value is a function.

In either case, the handler function is invoked with theevent argumentpassed to theeventTarget.dispatchEvent() function.

Async functions may be used as event listeners. If an async handler functionrejects, the rejection is captured and handled as described inEventTarget error handling.

An error thrown by one handler function does not prevent the other handlersfrom 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 theevent object.

functionhandler1(event) {console.log(event.type);// Prints 'foo'  event.a =1;}asyncfunctionhandler2(event) {console.log(event.type);// Prints 'foo'console.log(event.a);// Prints 1}const handler3 = {handleEvent(event) {console.log(event.type);// Prints 'foo'  },};const handler4 = {asynchandleEvent(event) {console.log(event.type);// Prints 'foo'  },};const target =newEventTarget();target.addEventListener('foo', handler1);target.addEventListener('foo', handler2);target.addEventListener('foo', handler3);target.addEventListener('foo', handler4, {once:true });

EventTarget error handling#

When a registered event listener throws (or returns a Promise that rejects),by default the error is treated as an uncaught exception onprocess.nextTick(). This means uncaught exceptions inEventTargets willterminate the Node.js process by default.

Throwing within an event listener willnot stop the other registered handlersfrom being invoked.

TheEventTarget does not implement any special default handling for'error'type events likeEventEmitter.

Currently errors are first forwarded to theprocess.on('error') eventbefore reachingprocess.on('uncaughtException'). This behavior isdeprecated and will change in a future release to alignEventTarget withother Node.js APIs. Any code relying on theprocess.on('error') event shouldbe aligned with the new behavior.

Class:Event#

History
VersionChanges
v15.0.0

TheEvent class is now available through the global object.

v14.5.0

Added in: v14.5.0

TheEvent object is an adaptation of theEvent Web API. Instancesare created internally by Node.js.

event.bubbles#
Added in: v14.5.0

This is not used in Node.js and is provided purely for completeness.

event.cancelBubble#
Added in: v14.5.0

Alias forevent.stopPropagation() if set totrue. This is not usedin Node.js and is provided purely for completeness.

event.cancelable#
Added in: v14.5.0
  • Type:<boolean> True if the event was created with thecancelable option.
event.composed#
Added in: v14.5.0

This is not used in Node.js and is provided purely for completeness.

event.composedPath()#
Added in: v14.5.0

Returns an array containing the currentEventTarget as the only entry orempty if the event is not being dispatched. This is not used inNode.js and is provided purely for completeness.

event.currentTarget#
Added in: v14.5.0

Alias forevent.target.

event.defaultPrevented#
Added in: v14.5.0

Istrue ifcancelable istrue andevent.preventDefault() has beencalled.

event.eventPhase#
Added in: v14.5.0
  • Type:<number> Returns0 while an event is not being dispatched,2 whileit is being dispatched.

This is not used in Node.js and is provided purely for completeness.

event.initEvent(type[, bubbles[, cancelable]])#
Added in: v19.5.0

Stability: 3 - Legacy: The WHATWG spec considers it deprecated and usersshouldn't use it at all.

Redundant with event constructors and incapable of settingcomposed.This is not used in Node.js and is provided purely for completeness.

event.isTrusted#
Added in: v14.5.0

The<AbortSignal>"abort" event is emitted withisTrusted set totrue. Thevalue isfalse in all other cases.

event.preventDefault()#
Added in: v14.5.0

Sets thedefaultPrevented property totrue ifcancelable istrue.

event.returnValue#
Added in: v14.5.0

Stability: 3 - Legacy: Useevent.defaultPrevented instead.

  • Type:<boolean> True if the event has not been canceled.

The value ofevent.returnValue is always the opposite ofevent.defaultPrevented.This is not used in Node.js and is provided purely for completeness.

event.srcElement#
Added in: v14.5.0

Stability: 3 - Legacy: Useevent.target instead.

Alias forevent.target.

event.stopImmediatePropagation()#
Added in: v14.5.0

Stops the invocation of event listeners after the current one completes.

event.stopPropagation()#
Added in: v14.5.0

This is not used in Node.js and is provided purely for completeness.

event.target#
Added in: v14.5.0
event.timeStamp#
Added in: v14.5.0

The millisecond timestamp when theEvent object was created.

event.type#
Added in: v14.5.0

The event type identifier.

Class:EventTarget#

History
VersionChanges
v15.0.0

TheEventTarget class is now available through the global object.

v14.5.0

Added in: v14.5.0

eventTarget.addEventListener(type, listener[, options])#
History
VersionChanges
v15.4.0

add support forsignal option.

v14.5.0

Added in: v14.5.0

  • type<string>
  • listener<Function> |<EventListener>
  • options<Object>
    • once<boolean> Whentrue, the listener is automatically removedwhen it is first invoked.Default:false.
    • passive<boolean> Whentrue, serves as a hint that the listener willnot call theEvent object'spreventDefault() method.Default:false.
    • capture<boolean> Not directly used by Node.js. Added for APIcompleteness.Default:false.
    • signal<AbortSignal> The listener will be removed when the givenAbortSignal object'sabort() method is called.

Adds a new handler for thetype event. Any givenlistener is addedonly once pertype and percapture option value.

If theonce option istrue, thelistener is removed after thenext time atype event is dispatched.

Thecapture option is not used by Node.js in any functional way other thantracking registered event listeners per theEventTarget specification.Specifically, thecapture option is used as part of the key when registeringalistener. Any individuallistener may be added once withcapture = false, and once withcapture = true.

functionhandler(event) {}const target =newEventTarget();target.addEventListener('foo', handler, {capture:true });// firsttarget.addEventListener('foo', handler, {capture:false });// second// Removes the second instance of handlertarget.removeEventListener('foo', handler);// Removes the first instance of handlertarget.removeEventListener('foo', handler, {capture:true });
eventTarget.dispatchEvent(event)#
Added in: v14.5.0
  • event<Event>
  • Returns:<boolean>true if either event'scancelable attribute value isfalse or itspreventDefault() method was not invoked, otherwisefalse.

Dispatches theevent to the list of handlers forevent.type.

The registered event listeners is synchronously invoked in the order theywere registered.

eventTarget.removeEventListener(type, listener[, options])#
Added in: v14.5.0

Removes thelistener from the list of handlers for eventtype.

Class:CustomEvent#

History
VersionChanges
v23.0.0

No longer experimental.

v22.1.0, v20.13.0

CustomEvent is now stable.

v19.0.0

No longer behind--experimental-global-customevent CLI flag.

v18.7.0, v16.17.0

Added in: v18.7.0, v16.17.0

TheCustomEvent object is an adaptation of theCustomEvent Web API.Instances are created internally by Node.js.

event.detail#
History
VersionChanges
v22.1.0, v20.13.0

CustomEvent is now stable.

v18.7.0, v16.17.0

Added in: v18.7.0, v16.17.0

  • Type:<any> Returns custom data passed when initializing.

Read-only.

Class:NodeEventTarget#

Added in: v14.5.0

TheNodeEventTarget is a Node.js-specific extension toEventTargetthat emulates a subset of theEventEmitter API.

nodeEventTarget.addListener(type, listener)#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that emulates theequivalentEventEmitter API. The only difference betweenaddListener() andaddEventListener() is thataddListener() will return a reference to theEventTarget.

nodeEventTarget.emit(type, arg)#
Added in: v15.2.0

Node.js-specific extension to theEventTarget class that dispatches thearg to the list of handlers fortype.

nodeEventTarget.eventNames()#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that returns an arrayof eventtype names for which event listeners are registered.

nodeEventTarget.listenerCount(type)#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that returns the numberof event listeners registered for thetype.

nodeEventTarget.setMaxListeners(n)#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that sets the numberof max event listeners asn.

nodeEventTarget.getMaxListeners()#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that returns the numberof max event listeners.

nodeEventTarget.off(type, listener[, options])#
Added in: v14.5.0

Node.js-specific alias foreventTarget.removeEventListener().

nodeEventTarget.on(type, listener)#
Added in: v14.5.0

Node.js-specific alias foreventTarget.addEventListener().

nodeEventTarget.once(type, listener)#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that adds aoncelistener for the given eventtype. This is equivalent to callingonwith theonce option set totrue.

nodeEventTarget.removeAllListeners([type])#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class. Iftype is specified,removes all registered listeners fortype, otherwise removes all registeredlisteners.

nodeEventTarget.removeListener(type, listener[, options])#
Added in: v14.5.0

Node.js-specific extension to theEventTarget class that removes thelistener for the giventype. The only difference betweenremoveListener()andremoveEventListener() is thatremoveListener() will return a referenceto theEventTarget.