{ "type": "module", "source": "doc/api/events.md", "modules": [ { "textRaw": "Events", "name": "Events", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "type": "module", "desc": "

Source Code: lib/events.js

\n

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.

\n

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.

\n

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.

\n

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 will be discarded.

\n

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.

\n
const EventEmitter = require('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
", "modules": [ { "textRaw": "Passing arguments and `this` to listeners", "name": "passing_arguments_and_`this`_to_listeners", "desc": "

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.

\n
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
\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:

\n
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
", "type": "module", "displayName": "Passing arguments and `this` to listeners" }, { "textRaw": "Asynchronous vs. synchronous", "name": "asynchronous_vs._synchronous", "desc": "

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:

\n
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
", "type": "module", "displayName": "Asynchronous vs. synchronous" }, { "textRaw": "Handling events only once", "name": "handling_events_only_once", "desc": "

When a listener is registered using the eventEmitter.on() method, that\nlistener will be invoked every time the named event is emitted.

\n
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
\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.

\n
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
", "type": "module", "displayName": "Handling events only once" }, { "textRaw": "Error events", "name": "error_events", "desc": "

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.

\n

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.

\n
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
\n

To guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the domain module is deprecated.)

\n

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

\n
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
\n

It is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol errorMonitor.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on(EventEmitter.errorMonitor, (err) => {\n  MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n
", "type": "module", "displayName": "Error events" }, { "textRaw": "Capture rejections of promises", "name": "capture_rejections_of_promises", "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:

\n
const ee = new EventEmitter();\nee.on('something', async (value) => {\n  throw new Error('kaboom');\n});\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.

\n
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
\n

Setting EventEmitter.captureRejections = true will change the default for all\nnew instances of EventEmitter.

\n
EventEmitter.captureRejections = true;\nconst ee1 = new EventEmitter();\nee1.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n
\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.

", "type": "module", "displayName": "Capture rejections of promises" }, { "textRaw": "`EventTarget` and `Event` API", "name": "`eventtarget`_and_`event`_api", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

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.\nNeither the EventTarget nor Event classes are available for end\nuser code to create.

\n
const target = getEventTargetSomehow();\n\ntarget.addEventListener('foo', (event) => {\n  console.log('foo event happened!');\n});\n
", "modules": [ { "textRaw": "Node.js `EventTarget` vs. DOM `EventTarget`", "name": "node.js_`eventtarget`_vs._dom_`eventtarget`", "desc": "

There are two key differences between the Node.js EventTarget and the\nEventTarget Web API:

\n
    \n
  1. Whereas DOM EventTarget instances may be hierarchical, there is no\nconcept of hierarchy and event propagation in Node.js. That is, an event\ndispatched to an EventTarget does not propagate through a hierarchy of\nnested target objects that may each have their own set of handlers for the\nevent.
  2. \n
  3. In the Node.js EventTarget, if an event listener is an async function\nor returns a Promise, and the returned Promise rejects, the rejection\nwill be automatically captured and handled the same way as a listener that\nthrows synchronously (see EventTarget error handling for details).
  4. \n
", "type": "module", "displayName": "Node.js `EventTarget` vs. DOM `EventTarget`" }, { "textRaw": "`NodeEventTarget` vs. `EventEmitter`", "name": "`nodeeventtarget`_vs._`eventemitter`", "desc": "

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.

\n
    \n
  1. Unlike EventEmitter, any given listener can be registered at most once\nper event type. Attempts to register a listener multiple times will be\nignored.
  2. \n
  3. The NodeEventTarget does not emulate the full EventEmitter API.\nSpecifically the prependListener(), prependOnceListener(),\nrawListeners(), setMaxListeners(), getMaxListeners(), and\nerrorMonitor APIs are not emulated. The 'newListener' and\n'removeListener' events will also not be emitted.
  4. \n
  5. The NodeEventTarget does not implement any special default behavior\nfor events with type 'error'.
  6. \n
  7. The NodeEventTarget supports EventListener objects as well as\nfunctions as handlers for all event types.
  8. \n
", "type": "module", "displayName": "`NodeEventTarget` vs. `EventEmitter`" }, { "textRaw": "Event listener", "name": "event_listener", "desc": "

Event listeners registered for an event type may either be JavaScript\nfunctions or objects with a handleEvent property whose value is a function.

\n

In either case, the handler function will be invoked with the event argument\npassed to the eventTarget.dispatchEvent() function.

\n

Async functions may be used as event listeners. If an async handler function\nrejects, the rejection will be captured and be will handled as described in\nEventTarget error handling.

\n

An error thrown by one handler function will not prevent the other handlers\nfrom being invoked.

\n

The return value of a handler function will be ignored.

\n

Handlers are always invoked in the order they were added.

\n

Handler functions may mutate the event object.

\n
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 = getEventTargetSomehow();\n\ntarget.addEventListener('foo', handler1);\ntarget.addEventListener('foo', handler2);\ntarget.addEventListener('foo', handler3);\ntarget.addEventListener('foo', handler4, { once: true });\n
", "type": "module", "displayName": "Event listener" }, { "textRaw": "`EventTarget` error handling", "name": "`eventtarget`_error_handling", "desc": "

When a registered event listener throws (or returns a Promise that rejects),\nby default the error will be forwarded to the process.on('error') event\non process.nextTick(). Throwing within an event listener will not stop\nthe other registered handlers from being invoked.

\n

The EventTarget does not implement any special default handling for\n'error' type events.

", "type": "module", "displayName": "`EventTarget` error handling" } ], "classes": [ { "textRaw": "Class: `Event`", "type": "class", "name": "Event", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The Event object is an adaptation of the Event Web API. Instances\nare created internally by Node.js.

", "properties": [ { "textRaw": "`bubbles` Type: {boolean} Always returns `false`.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "Always returns `false`." }, { "textRaw": "`cancelable` Type: {boolean} True if the event was created with the `cancelable` option.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "True if the event was created with the `cancelable` option." }, { "textRaw": "`composed` Type: {boolean} Always returns `false`.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "Always returns `false`." }, { "textRaw": "`currentTarget` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Alias for event.target.

", "shortDesc": "The `EventTarget` dispatching the event." }, { "textRaw": "`defaultPrevented` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Will be true if cancelable is true and event.preventDefault() has been\ncalled.

" }, { "textRaw": "`eventPhase` Type: {number} Returns `0` while an event is not being dispatched, `2` while it is being dispatched.", "type": "number", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "Returns `0` while an event is not being dispatched, `2` while it is being dispatched." }, { "textRaw": "`isTrusted` Type: {boolean} Always returns `false`.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "Always returns `false`." }, { "textRaw": "`returnValue` Type: {boolean} True if the event has not been canceled.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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

", "shortDesc": "True if the event has not been canceled." }, { "textRaw": "`srcElement` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Alias for event.target.

", "shortDesc": "The `EventTarget` dispatching the event." }, { "textRaw": "`target` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "The `EventTarget` dispatching the event." }, { "textRaw": "`timeStamp` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The millisecond timestamp when the Event object was created.

" }, { "textRaw": "`type` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The event type identifier.

" } ], "methods": [ { "textRaw": "`event.cancelBubble()`", "type": "method", "name": "cancelBubble", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Alias for event.stopPropagation(). This is not used in Node.js and is\nprovided purely for completeness.

" }, { "textRaw": "`event.composedPath()`", "type": "method", "name": "composedPath", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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.

" }, { "textRaw": "`event.preventDefault()`", "type": "method", "name": "preventDefault", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sets the defaultPrevented property to true if cancelable is true.

" }, { "textRaw": "`event.stopImmediatePropagation()`", "type": "method", "name": "stopImmediatePropagation", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" }, { "textRaw": "`event.stopPropagation()`", "type": "method", "name": "stopPropagation", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" } ] }, { "textRaw": "Class: `EventTarget`", "type": "class", "name": "EventTarget", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "methods": [ { "textRaw": "`eventTarget.addEventListener(type, listener[, options])`", "type": "method", "name": "addEventListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`once` {boolean} When `true`, the listener will be automatically removed when it is first invoked. **Default:** `false`.", "name": "once", "type": "boolean", "default": "`false`", "desc": "When `true`, the listener will be automatically removed when it is first invoked." }, { "textRaw": "`passive` {boolean} When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. **Default:** `false`.", "name": "passive", "type": "boolean", "default": "`false`", "desc": "When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method." }, { "textRaw": "`capture` {boolean} Not directly used by Node.js. Added for API completeness. **Default:** `false`.", "name": "capture", "type": "boolean", "default": "`false`", "desc": "Not directly used by Node.js. Added for API completeness." } ] } ] } ], "desc": "

Adds a new handler for the type event. Any given listener will be added\nonly once per type and per capture option value.

\n

If the once option is true, the listener will be removed after the\nnext time a type event is dispatched.

\n

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.

\n
function handler(event) {}\n\nconst target = getEventTargetSomehow();\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
" }, { "textRaw": "`eventTarget.dispatchEvent(event)`", "type": "method", "name": "dispatchEvent", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`event` {Object|Event}", "name": "event", "type": "Object|Event" } ] } ], "desc": "

Dispatches the event to the list of handlers for event.type. The event\nmay be an Event object or any object with a type property whose value is\na string.

\n

The registered event listeners will be synchronously invoked in the order they\nwere registered.

" }, { "textRaw": "`eventTarget.removeEventListener(type, listener)`", "type": "method", "name": "removeEventListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`capture` {boolean}", "name": "capture", "type": "boolean" } ] } ] } ], "desc": "

Removes the listener from the list of handlers for event type.

" } ] }, { "textRaw": "Class: `NodeEventTarget extends EventTarget`", "type": "class", "name": "NodeEventTarget", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The NodeEventTarget is a Node.js-specific extension to EventTarget\nthat emulates a subset of the EventEmitter API.

", "methods": [ { "textRaw": "`nodeEventTarget.addListener(type, listener[, options])`", "type": "method", "name": "addListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`once` {boolean}", "name": "once", "type": "boolean" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`nodeEventTarget.eventNames()`", "type": "method", "name": "eventNames", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Node.js-specific extension to the EventTarget class that returns an array\nof event type names for which event listeners are registered.

" }, { "textRaw": "`nodeEventTarget.listenerCount(type)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Node.js-specific extension to the EventTarget class that returns the number\nof event listeners registered for the type.

" }, { "textRaw": "`nodeEventTarget.off(type, listener)`", "type": "method", "name": "off", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" } ] } ], "desc": "

Node.js-speciic alias for eventTarget.removeListener().

" }, { "textRaw": "`nodeEventTarget.on(type, listener[, options])`", "type": "method", "name": "on", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`once` {boolean}", "name": "once", "type": "boolean" } ] } ] } ], "desc": "

Node.js-specific alias for eventTarget.addListener().

" }, { "textRaw": "`nodeEventTarget.once(type, listener[, options])`", "type": "method", "name": "once", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object" } ] } ], "desc": "

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.

" }, { "textRaw": "`nodeEventTarget.removeAllListeners([type])`", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Node.js-specific extension to the EventTarget class. If type is specified,\nremoves all registered listeners for type, otherwise removes all registered\nlisteners.

" }, { "textRaw": "`nodeEventTarget.removeListener(type, listener)`", "type": "method", "name": "removeListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" } ] } ], "desc": "

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.

" } ] } ], "type": "module", "displayName": "`EventTarget` and `Event` API" } ], "classes": [ { "textRaw": "Class: `EventEmitter`", "type": "class", "name": "EventEmitter", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": [ "v13.4.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/27867", "description": "Added captureRejections option." } ] }, "desc": "

The EventEmitter class is defined and exposed by the events module:

\n
const EventEmitter = require('events');\n
\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.

\n

It supports the following option:

\n", "events": [ { "textRaw": "Event: `'newListener'`", "type": "event", "name": "newListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event being listened for", "name": "eventName", "type": "string|symbol", "desc": "The name of the event being listened for" }, { "textRaw": "`listener` {Function} The event handler function", "name": "listener", "type": "Function", "desc": "The event handler function" } ], "desc": "

The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.

\n

Listeners registered for the 'newListener' event will be passed the event\nname and a reference to the listener being added.

\n

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 will be inserted before the\nlistener that is in the process of being added.

\n
const 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
" }, { "textRaw": "Event: `'removeListener'`", "type": "event", "name": "removeListener", "meta": { "added": [ "v0.9.3" ], "changes": [ { "version": "v6.1.0, v4.7.0", "pr-url": "https://github.com/nodejs/node/pull/6394", "description": "For listeners attached using `.once()`, the `listener` argument now yields the original listener function." } ] }, "params": [ { "textRaw": "`eventName` {string|symbol} The event name", "name": "eventName", "type": "string|symbol", "desc": "The event name" }, { "textRaw": "`listener` {Function} The event handler function", "name": "listener", "type": "Function", "desc": "The event handler function" } ], "desc": "

The 'removeListener' event is emitted after the listener is removed.

" } ], "methods": [ { "textRaw": "`EventEmitter.listenerCount(emitter, eventName)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v0.9.12" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter} The emitter to query", "name": "emitter", "type": "EventEmitter", "desc": "The emitter to query" }, { "textRaw": "`eventName` {string|symbol} The event name", "name": "eventName", "type": "string|symbol", "desc": "The event name" } ] } ], "desc": "

A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n// Prints: 2\n
" }, { "textRaw": "`emitter.addListener(eventName, listener)`", "type": "method", "name": "addListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Alias for emitter.on(eventName, listener).

" }, { "textRaw": "`emitter.emit(eventName[, ...args])`", "type": "method", "name": "emit", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.

\n

Returns true if the event had listeners, false otherwise.

\n
const EventEmitter = require('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
" }, { "textRaw": "`emitter.eventNames()`", "type": "method", "name": "eventNames", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Array}", "name": "return", "type": "Array" }, "params": [] } ], "desc": "

Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array will be strings or Symbols.

\n
const EventEmitter = require('events');\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
" }, { "textRaw": "`emitter.getMaxListeners()`", "type": "method", "name": "getMaxListeners", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nEventEmitter.defaultMaxListeners.

" }, { "textRaw": "`emitter.listenerCount(eventName)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v3.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event being listened for", "name": "eventName", "type": "string|symbol", "desc": "The name of the event being listened for" } ] } ], "desc": "

Returns the number of listeners listening to the event named eventName.

" }, { "textRaw": "`emitter.listeners(eventName)`", "type": "method", "name": "listeners", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/6881", "description": "For listeners attached using `.once()` this returns the original listeners instead of wrapper functions now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Returns a copy of the array of listeners for the event named eventName.

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n
" }, { "textRaw": "`emitter.off(eventName, listener)`", "type": "method", "name": "off", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Alias for emitter.removeListener().

" }, { "textRaw": "`emitter.on(eventName, listener)`", "type": "method", "name": "on", "meta": { "added": [ "v0.1.101" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event.", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function", "name": "listener", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

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.

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

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

\n

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.

\n
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
" }, { "textRaw": "`emitter.once(eventName, listener)`", "type": "method", "name": "once", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event.", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function", "name": "listener", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

Adds a one-time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.

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

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

\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.

\n
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
" }, { "textRaw": "`emitter.prependListener(eventName, listener)`", "type": "method", "name": "prependListener", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event.", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function", "name": "listener", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

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.

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

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

" }, { "textRaw": "`emitter.prependOnceListener(eventName, listener)`", "type": "method", "name": "prependOnceListener", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event.", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function", "name": "listener", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

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.

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

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

" }, { "textRaw": "`emitter.removeAllListeners([eventName])`", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Removes all listeners, or those of the specified eventName.

\n

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).

\n

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

" }, { "textRaw": "`emitter.removeListener(eventName, listener)`", "type": "method", "name": "removeListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Removes the specified listener from the listener array for the event named\neventName.

\n
const callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
\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.

\n

Once an event has been emitted, all listeners attached to it at the\ntime of emitting will be 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 will behave as expected.

\n
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
\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.

\n

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:

\n
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
\n

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

" }, { "textRaw": "`emitter.setMaxListeners(n)`", "type": "method", "name": "setMaxListeners", "meta": { "added": [ "v0.3.5" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`n` {integer}", "name": "n", "type": "integer" } ] } ], "desc": "

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.

\n

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

" }, { "textRaw": "`emitter.rawListeners(eventName)`", "type": "method", "name": "rawListeners", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).

\n
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
" } ], "properties": [ { "textRaw": "`EventEmitter.defaultMaxListeners`", "name": "defaultMaxListeners", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "desc": "

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 EventEmitter.defaultMaxListeners\nproperty can be used. If this value is not a positive number, a TypeError\nwill be thrown.

\n

Take caution when setting the EventEmitter.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 EventEmitter.defaultMaxListeners.

\n

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:

\n
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
\n

The --trace-warnings command line flag can be used to display the\nstack trace for such warnings.

\n

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'.

" }, { "textRaw": "`EventEmitter.errorMonitor`", "name": "errorMonitor", "meta": { "added": [ "v13.6.0", "v12.16.0" ], "changes": [] }, "desc": "

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.

\n

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.

" } ], "modules": [ { "textRaw": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`", "name": "`emitter[symbol.for('nodejs.rejection')](err,_eventname[,_...args])`", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "\n

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').

\n
const { EventEmitter, captureRejectionSymbol } = require('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
", "type": "module", "displayName": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`" } ] } ], "methods": [ { "textRaw": "`events.once(emitter, name)`", "type": "method", "name": "once", "meta": { "added": [ "v11.13.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`emitter` {EventEmitter}", "name": "emitter", "type": "EventEmitter" }, { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

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.

\n

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.

\n
const { once, EventEmitter } = require('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
\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:

\n
const { EventEmitter, once } = require('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
", "modules": [ { "textRaw": "Awaiting multiple events emitted on `process.nextTick()`", "name": "awaiting_multiple_events_emitted_on_`process.nexttick()`", "desc": "

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.

\n
const { EventEmitter, once } = require('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
\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():

\n
const { EventEmitter, once } = require('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
", "type": "module", "displayName": "Awaiting multiple events emitted on `process.nextTick()`" } ] }, { "textRaw": "`events.on(emitter, eventName)`", "type": "method", "name": "on", "meta": { "added": [ "v13.6.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`", "name": "return", "type": "AsyncIterator", "desc": "that iterates `eventName` events emitted by the `emitter`" }, "params": [ { "textRaw": "`emitter` {EventEmitter}", "name": "emitter", "type": "EventEmitter" }, { "textRaw": "`eventName` {string|symbol} The name of the event being listened for", "name": "eventName", "type": "string|symbol", "desc": "The name of the event being listened for" } ] } ], "desc": "
const { on, EventEmitter } = require('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
\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.

" } ], "properties": [ { "textRaw": "`events.captureRejections`", "name": "captureRejections", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Value: <boolean>

\n

Change the default captureRejections option on all new EventEmitter objects.

" }, { "textRaw": "`events.captureRejectionSymbol`", "name": "captureRejectionSymbol", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Value: Symbol.for('nodejs.rejection')

\n

See how to write a custom rejection handler.

" } ] } ] }