1# Events 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!--type=module--> 8 9<!-- source_link=lib/events.js --> 10 11Much of the Node.js core API is built around an idiomatic asynchronous 12event-driven architecture in which certain kinds of objects (called "emitters") 13emit named events that cause `Function` objects ("listeners") to be called. 14 15For instance: a [`net.Server`][] object emits an event each time a peer 16connects to it; a [`fs.ReadStream`][] emits an event when the file is opened; 17a [stream][] emits an event whenever data is available to be read. 18 19All objects that emit events are instances of the `EventEmitter` class. These 20objects expose an `eventEmitter.on()` function that allows one or more 21functions to be attached to named events emitted by the object. Typically, 22event names are camel-cased strings but any valid JavaScript property key 23can be used. 24 25When the `EventEmitter` object emits an event, all of the functions attached 26to that specific event are called _synchronously_. Any values returned by the 27called listeners are _ignored_ and discarded. 28 29The following example shows a simple `EventEmitter` instance with a single 30listener. The `eventEmitter.on()` method is used to register listeners, while 31the `eventEmitter.emit()` method is used to trigger the event. 32 33```js 34const EventEmitter = require('events'); 35 36class MyEmitter extends EventEmitter {} 37 38const myEmitter = new MyEmitter(); 39myEmitter.on('event', () => { 40 console.log('an event occurred!'); 41}); 42myEmitter.emit('event'); 43``` 44 45## Passing arguments and `this` to listeners 46 47The `eventEmitter.emit()` method allows an arbitrary set of arguments to be 48passed to the listener functions. Keep in mind that when 49an ordinary listener function is called, the standard `this` keyword 50is intentionally set to reference the `EventEmitter` instance to which the 51listener is attached. 52 53```js 54const myEmitter = new MyEmitter(); 55myEmitter.on('event', function(a, b) { 56 console.log(a, b, this, this === myEmitter); 57 // Prints: 58 // a b MyEmitter { 59 // domain: null, 60 // _events: { event: [Function] }, 61 // _eventsCount: 1, 62 // _maxListeners: undefined } true 63}); 64myEmitter.emit('event', 'a', 'b'); 65``` 66 67It is possible to use ES6 Arrow Functions as listeners, however, when doing so, 68the `this` keyword will no longer reference the `EventEmitter` instance: 69 70```js 71const myEmitter = new MyEmitter(); 72myEmitter.on('event', (a, b) => { 73 console.log(a, b, this); 74 // Prints: a b {} 75}); 76myEmitter.emit('event', 'a', 'b'); 77``` 78 79## Asynchronous vs. synchronous 80 81The `EventEmitter` calls all listeners synchronously in the order in which 82they were registered. This ensures the proper sequencing of 83events and helps avoid race conditions and logic errors. When appropriate, 84listener functions can switch to an asynchronous mode of operation using 85the `setImmediate()` or `process.nextTick()` methods: 86 87```js 88const myEmitter = new MyEmitter(); 89myEmitter.on('event', (a, b) => { 90 setImmediate(() => { 91 console.log('this happens asynchronously'); 92 }); 93}); 94myEmitter.emit('event', 'a', 'b'); 95``` 96 97## Handling events only once 98 99When a listener is registered using the `eventEmitter.on()` method, that 100listener is invoked _every time_ the named event is emitted. 101 102```js 103const myEmitter = new MyEmitter(); 104let m = 0; 105myEmitter.on('event', () => { 106 console.log(++m); 107}); 108myEmitter.emit('event'); 109// Prints: 1 110myEmitter.emit('event'); 111// Prints: 2 112``` 113 114Using the `eventEmitter.once()` method, it is possible to register a listener 115that is called at most once for a particular event. Once the event is emitted, 116the listener is unregistered and *then* called. 117 118```js 119const myEmitter = new MyEmitter(); 120let m = 0; 121myEmitter.once('event', () => { 122 console.log(++m); 123}); 124myEmitter.emit('event'); 125// Prints: 1 126myEmitter.emit('event'); 127// Ignored 128``` 129 130## Error events 131 132When an error occurs within an `EventEmitter` instance, the typical action is 133for an `'error'` event to be emitted. These are treated as special cases 134within Node.js. 135 136If an `EventEmitter` does _not_ have at least one listener registered for the 137`'error'` event, and an `'error'` event is emitted, the error is thrown, a 138stack trace is printed, and the Node.js process exits. 139 140```js 141const myEmitter = new MyEmitter(); 142myEmitter.emit('error', new Error('whoops!')); 143// Throws and crashes Node.js 144``` 145 146To guard against crashing the Node.js process the [`domain`][] module can be 147used. (Note, however, that the `domain` module is deprecated.) 148 149As a best practice, listeners should always be added for the `'error'` events. 150 151```js 152const myEmitter = new MyEmitter(); 153myEmitter.on('error', (err) => { 154 console.error('whoops! there was an error'); 155}); 156myEmitter.emit('error', new Error('whoops!')); 157// Prints: whoops! there was an error 158``` 159 160It is possible to monitor `'error'` events without consuming the emitted error 161by installing a listener using the symbol `events.errorMonitor`. 162 163```js 164const { EventEmitter, errorMonitor } = require('events'); 165 166const myEmitter = new EventEmitter(); 167myEmitter.on(errorMonitor, (err) => { 168 MyMonitoringTool.log(err); 169}); 170myEmitter.emit('error', new Error('whoops!')); 171// Still throws and crashes Node.js 172``` 173 174## Capture rejections of promises 175 176> Stability: 1 - captureRejections is experimental. 177 178Using `async` functions with event handlers is problematic, because it 179can lead to an unhandled rejection in case of a thrown exception: 180 181```js 182const ee = new EventEmitter(); 183ee.on('something', async (value) => { 184 throw new Error('kaboom'); 185}); 186``` 187 188The `captureRejections` option in the `EventEmitter` constructor or the global 189setting change this behavior, installing a `.then(undefined, handler)` 190handler on the `Promise`. This handler routes the exception 191asynchronously to the [`Symbol.for('nodejs.rejection')`][rejection] method 192if there is one, or to [`'error'`][error] event handler if there is none. 193 194```js 195const ee1 = new EventEmitter({ captureRejections: true }); 196ee1.on('something', async (value) => { 197 throw new Error('kaboom'); 198}); 199 200ee1.on('error', console.log); 201 202const ee2 = new EventEmitter({ captureRejections: true }); 203ee2.on('something', async (value) => { 204 throw new Error('kaboom'); 205}); 206 207ee2[Symbol.for('nodejs.rejection')] = console.log; 208``` 209 210Setting `events.captureRejections = true` will change the default for all 211new instances of `EventEmitter`. 212 213```js 214const events = require('events'); 215events.captureRejections = true; 216const ee1 = new events.EventEmitter(); 217ee1.on('something', async (value) => { 218 throw new Error('kaboom'); 219}); 220 221ee1.on('error', console.log); 222``` 223 224The `'error'` events that are generated by the `captureRejections` behavior 225do not have a catch handler to avoid infinite error loops: the 226recommendation is to **not use `async` functions as `'error'` event handlers**. 227 228## Class: `EventEmitter` 229<!-- YAML 230added: v0.1.26 231changes: 232 - version: 233 - v13.4.0 234 - v12.16.0 235 pr-url: https://github.com/nodejs/node/pull/27867 236 description: Added captureRejections option. 237--> 238 239The `EventEmitter` class is defined and exposed by the `events` module: 240 241```js 242const EventEmitter = require('events'); 243``` 244 245All `EventEmitter`s emit the event `'newListener'` when new listeners are 246added and `'removeListener'` when existing listeners are removed. 247 248It supports the following option: 249 250* `captureRejections` {boolean} It enables 251 [automatic capturing of promise rejection][capturerejections]. 252 **Default:** `false`. 253 254### Event: `'newListener'` 255<!-- YAML 256added: v0.1.26 257--> 258 259* `eventName` {string|symbol} The name of the event being listened for 260* `listener` {Function} The event handler function 261 262The `EventEmitter` instance will emit its own `'newListener'` event *before* 263a listener is added to its internal array of listeners. 264 265Listeners registered for the `'newListener'` event are passed the event 266name and a reference to the listener being added. 267 268The fact that the event is triggered before adding the listener has a subtle 269but important side effect: any *additional* listeners registered to the same 270`name` *within* the `'newListener'` callback are inserted *before* the 271listener that is in the process of being added. 272 273```js 274class MyEmitter extends EventEmitter {} 275 276const myEmitter = new MyEmitter(); 277// Only do this once so we don't loop forever 278myEmitter.once('newListener', (event, listener) => { 279 if (event === 'event') { 280 // Insert a new listener in front 281 myEmitter.on('event', () => { 282 console.log('B'); 283 }); 284 } 285}); 286myEmitter.on('event', () => { 287 console.log('A'); 288}); 289myEmitter.emit('event'); 290// Prints: 291// B 292// A 293``` 294 295### Event: `'removeListener'` 296<!-- YAML 297added: v0.9.3 298changes: 299 - version: 300 - v6.1.0 301 - v4.7.0 302 pr-url: https://github.com/nodejs/node/pull/6394 303 description: For listeners attached using `.once()`, the `listener` argument 304 now yields the original listener function. 305--> 306 307* `eventName` {string|symbol} The event name 308* `listener` {Function} The event handler function 309 310The `'removeListener'` event is emitted *after* the `listener` is removed. 311 312### `emitter.addListener(eventName, listener)` 313<!-- YAML 314added: v0.1.26 315--> 316 317* `eventName` {string|symbol} 318* `listener` {Function} 319 320Alias for `emitter.on(eventName, listener)`. 321 322### `emitter.emit(eventName[, ...args])` 323<!-- YAML 324added: v0.1.26 325--> 326 327* `eventName` {string|symbol} 328* `...args` {any} 329* Returns: {boolean} 330 331Synchronously calls each of the listeners registered for the event named 332`eventName`, in the order they were registered, passing the supplied arguments 333to each. 334 335Returns `true` if the event had listeners, `false` otherwise. 336 337```js 338const EventEmitter = require('events'); 339const myEmitter = new EventEmitter(); 340 341// First listener 342myEmitter.on('event', function firstListener() { 343 console.log('Helloooo! first listener'); 344}); 345// Second listener 346myEmitter.on('event', function secondListener(arg1, arg2) { 347 console.log(`event with parameters ${arg1}, ${arg2} in second listener`); 348}); 349// Third listener 350myEmitter.on('event', function thirdListener(...args) { 351 const parameters = args.join(', '); 352 console.log(`event with parameters ${parameters} in third listener`); 353}); 354 355console.log(myEmitter.listeners('event')); 356 357myEmitter.emit('event', 1, 2, 3, 4, 5); 358 359// Prints: 360// [ 361// [Function: firstListener], 362// [Function: secondListener], 363// [Function: thirdListener] 364// ] 365// Helloooo! first listener 366// event with parameters 1, 2 in second listener 367// event with parameters 1, 2, 3, 4, 5 in third listener 368``` 369 370### `emitter.eventNames()` 371<!-- YAML 372added: v6.0.0 373--> 374 375* Returns: {Array} 376 377Returns an array listing the events for which the emitter has registered 378listeners. The values in the array are strings or `Symbol`s. 379 380```js 381const EventEmitter = require('events'); 382const myEE = new EventEmitter(); 383myEE.on('foo', () => {}); 384myEE.on('bar', () => {}); 385 386const sym = Symbol('symbol'); 387myEE.on(sym, () => {}); 388 389console.log(myEE.eventNames()); 390// Prints: [ 'foo', 'bar', Symbol(symbol) ] 391``` 392 393### `emitter.getMaxListeners()` 394<!-- YAML 395added: v1.0.0 396--> 397 398* Returns: {integer} 399 400Returns the current max listener value for the `EventEmitter` which is either 401set by [`emitter.setMaxListeners(n)`][] or defaults to 402[`events.defaultMaxListeners`][]. 403 404### `emitter.listenerCount(eventName)` 405<!-- YAML 406added: v3.2.0 407--> 408 409* `eventName` {string|symbol} The name of the event being listened for 410* Returns: {integer} 411 412Returns the number of listeners listening to the event named `eventName`. 413 414### `emitter.listeners(eventName)` 415<!-- YAML 416added: v0.1.26 417changes: 418 - version: v7.0.0 419 pr-url: https://github.com/nodejs/node/pull/6881 420 description: For listeners attached using `.once()` this returns the 421 original listeners instead of wrapper functions now. 422--> 423 424* `eventName` {string|symbol} 425* Returns: {Function[]} 426 427Returns a copy of the array of listeners for the event named `eventName`. 428 429```js 430server.on('connection', (stream) => { 431 console.log('someone connected!'); 432}); 433console.log(util.inspect(server.listeners('connection'))); 434// Prints: [ [Function] ] 435``` 436 437### `emitter.off(eventName, listener)` 438<!-- YAML 439added: v10.0.0 440--> 441 442* `eventName` {string|symbol} 443* `listener` {Function} 444* Returns: {EventEmitter} 445 446Alias for [`emitter.removeListener()`][]. 447 448### `emitter.on(eventName, listener)` 449<!-- YAML 450added: v0.1.101 451--> 452 453* `eventName` {string|symbol} The name of the event. 454* `listener` {Function} The callback function 455* Returns: {EventEmitter} 456 457Adds the `listener` function to the end of the listeners array for the 458event named `eventName`. No checks are made to see if the `listener` has 459already been added. Multiple calls passing the same combination of `eventName` 460and `listener` will result in the `listener` being added, and called, multiple 461times. 462 463```js 464server.on('connection', (stream) => { 465 console.log('someone connected!'); 466}); 467``` 468 469Returns a reference to the `EventEmitter`, so that calls can be chained. 470 471By default, event listeners are invoked in the order they are added. The 472`emitter.prependListener()` method can be used as an alternative to add the 473event listener to the beginning of the listeners array. 474 475```js 476const myEE = new EventEmitter(); 477myEE.on('foo', () => console.log('a')); 478myEE.prependListener('foo', () => console.log('b')); 479myEE.emit('foo'); 480// Prints: 481// b 482// a 483``` 484 485### `emitter.once(eventName, listener)` 486<!-- YAML 487added: v0.3.0 488--> 489 490* `eventName` {string|symbol} The name of the event. 491* `listener` {Function} The callback function 492* Returns: {EventEmitter} 493 494Adds a **one-time** `listener` function for the event named `eventName`. The 495next time `eventName` is triggered, this listener is removed and then invoked. 496 497```js 498server.once('connection', (stream) => { 499 console.log('Ah, we have our first user!'); 500}); 501``` 502 503Returns a reference to the `EventEmitter`, so that calls can be chained. 504 505By default, event listeners are invoked in the order they are added. The 506`emitter.prependOnceListener()` method can be used as an alternative to add the 507event listener to the beginning of the listeners array. 508 509```js 510const myEE = new EventEmitter(); 511myEE.once('foo', () => console.log('a')); 512myEE.prependOnceListener('foo', () => console.log('b')); 513myEE.emit('foo'); 514// Prints: 515// b 516// a 517``` 518 519### `emitter.prependListener(eventName, listener)` 520<!-- YAML 521added: v6.0.0 522--> 523 524* `eventName` {string|symbol} The name of the event. 525* `listener` {Function} The callback function 526* Returns: {EventEmitter} 527 528Adds the `listener` function to the *beginning* of the listeners array for the 529event named `eventName`. No checks are made to see if the `listener` has 530already been added. Multiple calls passing the same combination of `eventName` 531and `listener` will result in the `listener` being added, and called, multiple 532times. 533 534```js 535server.prependListener('connection', (stream) => { 536 console.log('someone connected!'); 537}); 538``` 539 540Returns a reference to the `EventEmitter`, so that calls can be chained. 541 542### `emitter.prependOnceListener(eventName, listener)` 543<!-- YAML 544added: v6.0.0 545--> 546 547* `eventName` {string|symbol} The name of the event. 548* `listener` {Function} The callback function 549* Returns: {EventEmitter} 550 551Adds a **one-time** `listener` function for the event named `eventName` to the 552*beginning* of the listeners array. The next time `eventName` is triggered, this 553listener is removed, and then invoked. 554 555```js 556server.prependOnceListener('connection', (stream) => { 557 console.log('Ah, we have our first user!'); 558}); 559``` 560 561Returns a reference to the `EventEmitter`, so that calls can be chained. 562 563### `emitter.removeAllListeners([eventName])` 564<!-- YAML 565added: v0.1.26 566--> 567 568* `eventName` {string|symbol} 569* Returns: {EventEmitter} 570 571Removes all listeners, or those of the specified `eventName`. 572 573It is bad practice to remove listeners added elsewhere in the code, 574particularly when the `EventEmitter` instance was created by some other 575component or module (e.g. sockets or file streams). 576 577Returns a reference to the `EventEmitter`, so that calls can be chained. 578 579### `emitter.removeListener(eventName, listener)` 580<!-- YAML 581added: v0.1.26 582--> 583 584* `eventName` {string|symbol} 585* `listener` {Function} 586* Returns: {EventEmitter} 587 588Removes the specified `listener` from the listener array for the event named 589`eventName`. 590 591```js 592const callback = (stream) => { 593 console.log('someone connected!'); 594}; 595server.on('connection', callback); 596// ... 597server.removeListener('connection', callback); 598``` 599 600`removeListener()` will remove, at most, one instance of a listener from the 601listener array. If any single listener has been added multiple times to the 602listener array for the specified `eventName`, then `removeListener()` must be 603called multiple times to remove each instance. 604 605Once an event is emitted, all listeners attached to it at the 606time of emitting are called in order. This implies that any 607`removeListener()` or `removeAllListeners()` calls *after* emitting and 608*before* the last listener finishes execution will not remove them from 609`emit()` in progress. Subsequent events behave as expected. 610 611```js 612const myEmitter = new MyEmitter(); 613 614const callbackA = () => { 615 console.log('A'); 616 myEmitter.removeListener('event', callbackB); 617}; 618 619const callbackB = () => { 620 console.log('B'); 621}; 622 623myEmitter.on('event', callbackA); 624 625myEmitter.on('event', callbackB); 626 627// callbackA removes listener callbackB but it will still be called. 628// Internal listener array at time of emit [callbackA, callbackB] 629myEmitter.emit('event'); 630// Prints: 631// A 632// B 633 634// callbackB is now removed. 635// Internal listener array [callbackA] 636myEmitter.emit('event'); 637// Prints: 638// A 639``` 640 641Because listeners are managed using an internal array, calling this will 642change the position indices of any listener registered *after* the listener 643being removed. This will not impact the order in which listeners are called, 644but it means that any copies of the listener array as returned by 645the `emitter.listeners()` method will need to be recreated. 646 647When a single function has been added as a handler multiple times for a single 648event (as in the example below), `removeListener()` will remove the most 649recently added instance. In the example the `once('ping')` 650listener is removed: 651 652```js 653const ee = new EventEmitter(); 654 655function pong() { 656 console.log('pong'); 657} 658 659ee.on('ping', pong); 660ee.once('ping', pong); 661ee.removeListener('ping', pong); 662 663ee.emit('ping'); 664ee.emit('ping'); 665``` 666 667Returns a reference to the `EventEmitter`, so that calls can be chained. 668 669### `emitter.setMaxListeners(n)` 670<!-- YAML 671added: v0.3.5 672--> 673 674* `n` {integer} 675* Returns: {EventEmitter} 676 677By default `EventEmitter`s will print a warning if more than `10` listeners are 678added for a particular event. This is a useful default that helps finding 679memory leaks. The `emitter.setMaxListeners()` method allows the limit to be 680modified for this specific `EventEmitter` instance. The value can be set to 681`Infinity` (or `0`) to indicate an unlimited number of listeners. 682 683Returns a reference to the `EventEmitter`, so that calls can be chained. 684 685### `emitter.rawListeners(eventName)` 686<!-- YAML 687added: v9.4.0 688--> 689 690* `eventName` {string|symbol} 691* Returns: {Function[]} 692 693Returns a copy of the array of listeners for the event named `eventName`, 694including any wrappers (such as those created by `.once()`). 695 696```js 697const emitter = new EventEmitter(); 698emitter.once('log', () => console.log('log once')); 699 700// Returns a new Array with a function `onceWrapper` which has a property 701// `listener` which contains the original listener bound above 702const listeners = emitter.rawListeners('log'); 703const logFnWrapper = listeners[0]; 704 705// Logs "log once" to the console and does not unbind the `once` event 706logFnWrapper.listener(); 707 708// Logs "log once" to the console and removes the listener 709logFnWrapper(); 710 711emitter.on('log', () => console.log('log persistently')); 712// Will return a new Array with a single function bound by `.on()` above 713const newListeners = emitter.rawListeners('log'); 714 715// Logs "log persistently" twice 716newListeners[0](); 717emitter.emit('log'); 718``` 719 720### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` 721<!-- YAML 722added: 723 - v13.4.0 724 - v12.16.0 725--> 726 727> Stability: 1 - captureRejections is experimental. 728 729* `err` Error 730* `eventName` {string|symbol} 731* `...args` {any} 732 733The `Symbol.for('nodejs.rejection')` method is called in case a 734promise rejection happens when emitting an event and 735[`captureRejections`][capturerejections] is enabled on the emitter. 736It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in 737place of `Symbol.for('nodejs.rejection')`. 738 739```js 740const { EventEmitter, captureRejectionSymbol } = require('events'); 741 742class MyClass extends EventEmitter { 743 constructor() { 744 super({ captureRejections: true }); 745 } 746 747 [captureRejectionSymbol](err, event, ...args) { 748 console.log('rejection happened for', event, 'with', err, ...args); 749 this.destroy(err); 750 } 751 752 destroy(err) { 753 // Tear the resource down here. 754 } 755} 756``` 757 758## `events.defaultMaxListeners` 759<!-- YAML 760added: v0.11.2 761--> 762 763By default, a maximum of `10` listeners can be registered for any single 764event. This limit can be changed for individual `EventEmitter` instances 765using the [`emitter.setMaxListeners(n)`][] method. To change the default 766for *all* `EventEmitter` instances, the `events.defaultMaxListeners` 767property can be used. If this value is not a positive number, a `RangeError` 768is thrown. 769 770Take caution when setting the `events.defaultMaxListeners` because the 771change affects *all* `EventEmitter` instances, including those created before 772the change is made. However, calling [`emitter.setMaxListeners(n)`][] still has 773precedence over `events.defaultMaxListeners`. 774 775This is not a hard limit. The `EventEmitter` instance will allow 776more listeners to be added but will output a trace warning to stderr indicating 777that a "possible EventEmitter memory leak" has been detected. For any single 778`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` 779methods can be used to temporarily avoid this warning: 780 781```js 782emitter.setMaxListeners(emitter.getMaxListeners() + 1); 783emitter.once('event', () => { 784 // do stuff 785 emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); 786}); 787``` 788 789The [`--trace-warnings`][] command-line flag can be used to display the 790stack trace for such warnings. 791 792The emitted warning can be inspected with [`process.on('warning')`][] and will 793have the additional `emitter`, `type` and `count` properties, referring to 794the event emitter instance, the event’s name and the number of attached 795listeners, respectively. 796Its `name` property is set to `'MaxListenersExceededWarning'`. 797 798## `events.errorMonitor` 799<!-- YAML 800added: 801 - v13.6.0 802 - v12.17.0 803--> 804 805This symbol shall be used to install a listener for only monitoring `'error'` 806events. Listeners installed using this symbol are called before the regular 807`'error'` listeners are called. 808 809Installing a listener using this symbol does not change the behavior once an 810`'error'` event is emitted, therefore the process will still crash if no 811regular `'error'` listener is installed. 812 813## `events.getEventListeners(emitterOrTarget, eventName)` 814<!-- YAML 815added: 816 - v14.17.0 817--> 818* `emitterOrTarget` {EventEmitter|EventTarget} 819* `eventName` {string|symbol} 820* Returns: {Function[]} 821 822Returns a copy of the array of listeners for the event named `eventName`. 823 824For `EventEmitter`s this behaves exactly the same as calling `.listeners` on 825the emitter. 826 827For `EventTarget`s this is the only way to get the event listeners for the 828event target. This is useful for debugging and diagnostic purposes. 829 830```js 831const { getEventListeners, EventEmitter } = require('events'); 832 833{ 834 const ee = new EventEmitter(); 835 const listener = () => console.log('Events are fun'); 836 ee.on('foo', listener); 837 getEventListeners(ee, 'foo'); // [listener] 838} 839{ 840 const et = new EventTarget(); 841 const listener = () => console.log('Events are fun'); 842 et.addEventListener('foo', listener); 843 getEventListeners(et, 'foo'); // [listener] 844} 845``` 846 847## `events.once(emitter, name[, options])` 848<!-- YAML 849added: 850 - v11.13.0 851 - v10.16.0 852changes: 853 - version: v14.17.0 854 pr-url: https://github.com/nodejs/node/pull/34912 855 description: The `signal` option is supported now. 856--> 857 858* `emitter` {EventEmitter} 859* `name` {string} 860* `options` {Object} 861 * `signal` {AbortSignal} Can be used to cancel waiting for the event. 862* Returns: {Promise} 863 864Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given 865event or that is rejected if the `EventEmitter` emits `'error'` while waiting. 866The `Promise` will resolve with an array of all the arguments emitted to the 867given event. 868 869This method is intentionally generic and works with the web platform 870[EventTarget][WHATWG-EventTarget] interface, which has no special 871`'error'` event semantics and does not listen to the `'error'` event. 872 873```js 874const { once, EventEmitter } = require('events'); 875 876async function run() { 877 const ee = new EventEmitter(); 878 879 process.nextTick(() => { 880 ee.emit('myevent', 42); 881 }); 882 883 const [value] = await once(ee, 'myevent'); 884 console.log(value); 885 886 const err = new Error('kaboom'); 887 process.nextTick(() => { 888 ee.emit('error', err); 889 }); 890 891 try { 892 await once(ee, 'myevent'); 893 } catch (err) { 894 console.log('error happened', err); 895 } 896} 897 898run(); 899``` 900 901The special handling of the `'error'` event is only used when `events.once()` 902is used to wait for another event. If `events.once()` is used to wait for the 903'`error'` event itself, then it is treated as any other kind of event without 904special handling: 905 906```js 907const { EventEmitter, once } = require('events'); 908 909const ee = new EventEmitter(); 910 911once(ee, 'error') 912 .then(([err]) => console.log('ok', err.message)) 913 .catch((err) => console.log('error', err.message)); 914 915ee.emit('error', new Error('boom')); 916 917// Prints: ok boom 918``` 919 920An {AbortSignal} can be used to cancel waiting for the event: 921 922```js 923const { EventEmitter, once } = require('events'); 924 925const ee = new EventEmitter(); 926const ac = new AbortController(); 927 928async function foo(emitter, event, signal) { 929 try { 930 await once(emitter, event, { signal }); 931 console.log('event emitted!'); 932 } catch (error) { 933 if (error.name === 'AbortError') { 934 console.error('Waiting for the event was canceled!'); 935 } else { 936 console.error('There was an error', error.message); 937 } 938 } 939} 940 941foo(ee, 'foo', ac.signal); 942ac.abort(); // Abort waiting for the event 943ee.emit('foo'); // Prints: Waiting for the event was canceled! 944``` 945 946### Awaiting multiple events emitted on `process.nextTick()` 947 948There is an edge case worth noting when using the `events.once()` function 949to await multiple events emitted on in the same batch of `process.nextTick()` 950operations, or whenever multiple events are emitted synchronously. Specifically, 951because the `process.nextTick()` queue is drained before the `Promise` microtask 952queue, and because `EventEmitter` emits all events synchronously, it is possible 953for `events.once()` to miss an event. 954 955```js 956const { EventEmitter, once } = require('events'); 957 958const myEE = new EventEmitter(); 959 960async function foo() { 961 await once(myEE, 'bar'); 962 console.log('bar'); 963 964 // This Promise will never resolve because the 'foo' event will 965 // have already been emitted before the Promise is created. 966 await once(myEE, 'foo'); 967 console.log('foo'); 968} 969 970process.nextTick(() => { 971 myEE.emit('bar'); 972 myEE.emit('foo'); 973}); 974 975foo().then(() => console.log('done')); 976``` 977 978To catch both events, create each of the Promises *before* awaiting either 979of them, then it becomes possible to use `Promise.all()`, `Promise.race()`, 980or `Promise.allSettled()`: 981 982```js 983const { EventEmitter, once } = require('events'); 984 985const myEE = new EventEmitter(); 986 987async function foo() { 988 await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]); 989 console.log('foo', 'bar'); 990} 991 992process.nextTick(() => { 993 myEE.emit('bar'); 994 myEE.emit('foo'); 995}); 996 997foo().then(() => console.log('done')); 998``` 999 1000## `events.captureRejections` 1001<!-- YAML 1002added: 1003 - v13.4.0 1004 - v12.16.0 1005--> 1006 1007> Stability: 1 - captureRejections is experimental. 1008 1009Value: {boolean} 1010 1011Change the default `captureRejections` option on all new `EventEmitter` objects. 1012 1013## `events.captureRejectionSymbol` 1014<!-- YAML 1015added: 1016 - v13.4.0 1017 - v12.16.0 1018--> 1019 1020> Stability: 1 - captureRejections is experimental. 1021 1022Value: `Symbol.for('nodejs.rejection')` 1023 1024See how to write a custom [rejection handler][rejection]. 1025 1026## `events.listenerCount(emitter, eventName)` 1027<!-- YAML 1028added: v0.9.12 1029deprecated: v3.2.0 1030--> 1031 1032> Stability: 0 - Deprecated: Use [`emitter.listenerCount()`][] instead. 1033 1034* `emitter` {EventEmitter} The emitter to query 1035* `eventName` {string|symbol} The event name 1036 1037A class method that returns the number of listeners for the given `eventName` 1038registered on the given `emitter`. 1039 1040```js 1041const { EventEmitter, listenerCount } = require('events'); 1042const myEmitter = new EventEmitter(); 1043myEmitter.on('event', () => {}); 1044myEmitter.on('event', () => {}); 1045console.log(listenerCount(myEmitter, 'event')); 1046// Prints: 2 1047``` 1048 1049## `events.on(emitter, eventName[, options])` 1050<!-- YAML 1051added: 1052 - v13.6.0 1053 - v12.16.0 1054--> 1055 1056* `emitter` {EventEmitter} 1057* `eventName` {string|symbol} The name of the event being listened for 1058* `options` {Object} 1059 * `signal` {AbortSignal} Can be used to cancel awaiting events. 1060* Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter` 1061 1062```js 1063const { on, EventEmitter } = require('events'); 1064 1065(async () => { 1066 const ee = new EventEmitter(); 1067 1068 // Emit later on 1069 process.nextTick(() => { 1070 ee.emit('foo', 'bar'); 1071 ee.emit('foo', 42); 1072 }); 1073 1074 for await (const event of on(ee, 'foo')) { 1075 // The execution of this inner block is synchronous and it 1076 // processes one event at a time (even with await). Do not use 1077 // if concurrent execution is required. 1078 console.log(event); // prints ['bar'] [42] 1079 } 1080 // Unreachable here 1081})(); 1082``` 1083 1084Returns an `AsyncIterator` that iterates `eventName` events. It will throw 1085if the `EventEmitter` emits `'error'`. It removes all listeners when 1086exiting the loop. The `value` returned by each iteration is an array 1087composed of the emitted event arguments. 1088 1089An {AbortSignal} can be used to cancel waiting on events: 1090 1091```js 1092const { on, EventEmitter } = require('events'); 1093const ac = new AbortController(); 1094 1095(async () => { 1096 const ee = new EventEmitter(); 1097 1098 // Emit later on 1099 process.nextTick(() => { 1100 ee.emit('foo', 'bar'); 1101 ee.emit('foo', 42); 1102 }); 1103 1104 for await (const event of on(ee, 'foo', { signal: ac.signal })) { 1105 // The execution of this inner block is synchronous and it 1106 // processes one event at a time (even with await). Do not use 1107 // if concurrent execution is required. 1108 console.log(event); // prints ['bar'] [42] 1109 } 1110 // Unreachable here 1111})(); 1112 1113process.nextTick(() => ac.abort()); 1114``` 1115 1116## `events.setMaxListeners(n[, ...eventTargets])` 1117<!-- YAML 1118added: v14.17.0 1119--> 1120 1121* `n` {number} A non-negative number. The maximum number of listeners per 1122 `EventTarget` event. 1123* `...eventsTargets` {EventTarget[]|EventEmitter[]} Zero or more {EventTarget} 1124 or {EventEmitter} instances. If none are specified, `n` is set as the default 1125 max for all newly created {EventTarget} and {EventEmitter} objects. 1126 1127```js 1128const { 1129 setMaxListeners, 1130 EventEmitter 1131} = require('events'); 1132 1133const target = new EventTarget(); 1134const emitter = new EventEmitter(); 1135 1136setMaxListeners(5, target, emitter); 1137``` 1138 1139<a id="event-target-and-event-api"></a> 1140## `EventTarget` and `Event` API 1141<!-- YAML 1142added: v14.5.0 1143--> 1144 1145> Stability: 1 - Experimental 1146 1147The `EventTarget` and `Event` objects are a Node.js-specific implementation 1148of the [`EventTarget` Web API][] that are exposed by some Node.js core APIs. 1149Neither the `EventTarget` nor `Event` classes are available for end 1150user code to create. 1151 1152```js 1153const target = getEventTargetSomehow(); 1154 1155target.addEventListener('foo', (event) => { 1156 console.log('foo event happened!'); 1157}); 1158``` 1159 1160### Node.js `EventTarget` vs. DOM `EventTarget` 1161 1162There are two key differences between the Node.js `EventTarget` and the 1163[`EventTarget` Web API][]: 1164 11651. Whereas DOM `EventTarget` instances *may* be hierarchical, there is no 1166 concept of hierarchy and event propagation in Node.js. That is, an event 1167 dispatched to an `EventTarget` does not propagate through a hierarchy of 1168 nested target objects that may each have their own set of handlers for the 1169 event. 11702. In the Node.js `EventTarget`, if an event listener is an async function 1171 or returns a `Promise`, and the returned `Promise` rejects, the rejection 1172 is automatically captured and handled the same way as a listener that 1173 throws synchronously (see [`EventTarget` error handling][] for details). 1174 1175### `NodeEventTarget` vs. `EventEmitter` 1176 1177The `NodeEventTarget` object implements a modified subset of the 1178`EventEmitter` API that allows it to closely *emulate* an `EventEmitter` in 1179certain situations. A `NodeEventTarget` is *not* an instance of `EventEmitter` 1180and cannot be used in place of an `EventEmitter` in most cases. 1181 11821. Unlike `EventEmitter`, any given `listener` can be registered at most once 1183 per event `type`. Attempts to register a `listener` multiple times are 1184 ignored. 11852. The `NodeEventTarget` does not emulate the full `EventEmitter` API. 1186 Specifically the `prependListener()`, `prependOnceListener()`, 1187 `rawListeners()`, `setMaxListeners()`, `getMaxListeners()`, and 1188 `errorMonitor` APIs are not emulated. The `'newListener'` and 1189 `'removeListener'` events will also not be emitted. 11903. The `NodeEventTarget` does not implement any special default behavior 1191 for events with type `'error'`. 11923. The `NodeEventTarget` supports `EventListener` objects as well as 1193 functions as handlers for all event types. 1194 1195### Event listener 1196 1197Event listeners registered for an event `type` may either be JavaScript 1198functions or objects with a `handleEvent` property whose value is a function. 1199 1200In either case, the handler function is invoked with the `event` argument 1201passed to the `eventTarget.dispatchEvent()` function. 1202 1203Async functions may be used as event listeners. If an async handler function 1204rejects, the rejection is captured and handled as described in 1205[`EventTarget` error handling][]. 1206 1207An error thrown by one handler function does not prevent the other handlers 1208from being invoked. 1209 1210The return value of a handler function is ignored. 1211 1212Handlers are always invoked in the order they were added. 1213 1214Handler functions may mutate the `event` object. 1215 1216```js 1217function handler1(event) { 1218 console.log(event.type); // Prints 'foo' 1219 event.a = 1; 1220} 1221 1222async function handler2(event) { 1223 console.log(event.type); // Prints 'foo' 1224 console.log(event.a); // Prints 1 1225} 1226 1227const handler3 = { 1228 handleEvent(event) { 1229 console.log(event.type); // Prints 'foo' 1230 } 1231}; 1232 1233const handler4 = { 1234 async handleEvent(event) { 1235 console.log(event.type); // Prints 'foo' 1236 } 1237}; 1238 1239const target = getEventTargetSomehow(); 1240 1241target.addEventListener('foo', handler1); 1242target.addEventListener('foo', handler2); 1243target.addEventListener('foo', handler3); 1244target.addEventListener('foo', handler4, { once: true }); 1245``` 1246 1247### `EventTarget` error handling 1248 1249When a registered event listener throws (or returns a Promise that rejects), 1250by default the error is treated as an uncaught exception on 1251`process.nextTick()`. This means uncaught exceptions in `EventTarget`s will 1252terminate the Node.js process by default. 1253 1254Throwing within an event listener will *not* stop the other registered handlers 1255from being invoked. 1256 1257The `EventTarget` does not implement any special default handling for `'error'` 1258type events like `EventEmitter`. 1259 1260Currently errors are first forwarded to the `process.on('error')` event 1261before reaching `process.on('uncaughtException')`. This behavior is 1262deprecated and will change in a future release to align `EventTarget` with 1263other Node.js APIs. Any code relying on the `process.on('error')` event should 1264be aligned with the new behavior. 1265 1266### Class: `Event` 1267<!-- YAML 1268added: v14.5.0 1269--> 1270 1271The `Event` object is an adaptation of the [`Event` Web API][]. Instances 1272are created internally by Node.js. 1273 1274#### `event.bubbles` 1275<!-- YAML 1276added: v14.5.0 1277--> 1278 1279* Type: {boolean} Always returns `false`. 1280 1281This is not used in Node.js and is provided purely for completeness. 1282 1283#### `event.cancelBubble()` 1284<!-- YAML 1285added: v14.5.0 1286--> 1287 1288Alias for `event.stopPropagation()`. This is not used in Node.js and is 1289provided purely for completeness. 1290 1291#### `event.cancelable` 1292<!-- YAML 1293added: v14.5.0 1294--> 1295 1296* Type: {boolean} True if the event was created with the `cancelable` option. 1297 1298#### `event.composed` 1299<!-- YAML 1300added: v14.5.0 1301--> 1302 1303* Type: {boolean} Always returns `false`. 1304 1305This is not used in Node.js and is provided purely for completeness. 1306 1307#### `event.composedPath()` 1308<!-- YAML 1309added: v14.5.0 1310--> 1311 1312Returns an array containing the current `EventTarget` as the only entry or 1313empty if the event is not being dispatched. This is not used in 1314Node.js and is provided purely for completeness. 1315 1316#### `event.currentTarget` 1317<!-- YAML 1318added: v14.5.0 1319--> 1320 1321* Type: {EventTarget} The `EventTarget` dispatching the event. 1322 1323Alias for `event.target`. 1324 1325#### `event.defaultPrevented` 1326<!-- YAML 1327added: v14.5.0 1328--> 1329 1330* Type: {boolean} 1331 1332Is `true` if `cancelable` is `true` and `event.preventDefault()` has been 1333called. 1334 1335#### `event.eventPhase` 1336<!-- YAML 1337added: v14.5.0 1338--> 1339 1340* Type: {number} Returns `0` while an event is not being dispatched, `2` while 1341 it is being dispatched. 1342 1343This is not used in Node.js and is provided purely for completeness. 1344 1345#### `event.isTrusted` 1346<!-- YAML 1347added: v14.5.0 1348--> 1349 1350* Type: {boolean} 1351 1352The {AbortSignal} `"abort"` event is emitted with `isTrusted` set to `true`. The 1353value is `false` in all other cases. 1354 1355#### `event.preventDefault()` 1356<!-- YAML 1357added: v14.5.0 1358--> 1359 1360Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. 1361 1362#### `event.returnValue` 1363<!-- YAML 1364added: v14.5.0 1365--> 1366 1367* Type: {boolean} True if the event has not been canceled. 1368 1369This is not used in Node.js and is provided purely for completeness. 1370 1371#### `event.srcElement` 1372<!-- YAML 1373added: v14.5.0 1374--> 1375 1376* Type: {EventTarget} The `EventTarget` dispatching the event. 1377 1378Alias for `event.target`. 1379 1380#### `event.stopImmediatePropagation()` 1381<!-- YAML 1382added: v14.5.0 1383--> 1384 1385Stops the invocation of event listeners after the current one completes. 1386 1387#### `event.stopPropagation()` 1388<!-- YAML 1389added: v14.5.0 1390--> 1391 1392This is not used in Node.js and is provided purely for completeness. 1393 1394#### `event.target` 1395<!-- YAML 1396added: v14.5.0 1397--> 1398 1399* Type: {EventTarget} The `EventTarget` dispatching the event. 1400 1401#### `event.timeStamp` 1402<!-- YAML 1403added: v14.5.0 1404--> 1405 1406* Type: {number} 1407 1408The millisecond timestamp when the `Event` object was created. 1409 1410#### `event.type` 1411<!-- YAML 1412added: v14.5.0 1413--> 1414 1415* Type: {string} 1416 1417The event type identifier. 1418 1419### Class: `EventTarget` 1420<!-- YAML 1421added: v14.5.0 1422--> 1423 1424#### `eventTarget.addEventListener(type, listener[, options])` 1425<!-- YAML 1426added: v14.5.0 1427--> 1428 1429* `type` {string} 1430* `listener` {Function|EventListener} 1431* `options` {Object} 1432 * `once` {boolean} When `true`, the listener is automatically removed 1433 when it is first invoked. **Default:** `false`. 1434 * `passive` {boolean} When `true`, serves as a hint that the listener will 1435 not call the `Event` object's `preventDefault()` method. 1436 **Default:** `false`. 1437 * `capture` {boolean} Not directly used by Node.js. Added for API 1438 completeness. **Default:** `false`. 1439 1440Adds a new handler for the `type` event. Any given `listener` is added 1441only once per `type` and per `capture` option value. 1442 1443If the `once` option is `true`, the `listener` is removed after the 1444next time a `type` event is dispatched. 1445 1446The `capture` option is not used by Node.js in any functional way other than 1447tracking registered event listeners per the `EventTarget` specification. 1448Specifically, the `capture` option is used as part of the key when registering 1449a `listener`. Any individual `listener` may be added once with 1450`capture = false`, and once with `capture = true`. 1451 1452```js 1453function handler(event) {} 1454 1455const target = getEventTargetSomehow(); 1456target.addEventListener('foo', handler, { capture: true }); // first 1457target.addEventListener('foo', handler, { capture: false }); // second 1458 1459// Removes the second instance of handler 1460target.removeEventListener('foo', handler); 1461 1462// Removes the first instance of handler 1463target.removeEventListener('foo', handler, { capture: true }); 1464``` 1465 1466#### `eventTarget.dispatchEvent(event)` 1467<!-- YAML 1468added: v14.5.0 1469--> 1470 1471* `event` {Event} 1472* Returns: {boolean} `true` if either event’s `cancelable` attribute value is 1473 false or its `preventDefault()` method was not invoked, otherwise `false`. 1474 1475Dispatches the `event` to the list of handlers for `event.type`. 1476 1477The registered event listeners is synchronously invoked in the order they 1478were registered. 1479 1480#### `eventTarget.removeEventListener(type, listener)` 1481<!-- YAML 1482added: v14.5.0 1483--> 1484 1485* `type` {string} 1486* `listener` {Function|EventListener} 1487* `options` {Object} 1488 * `capture` {boolean} 1489 1490Removes the `listener` from the list of handlers for event `type`. 1491 1492### Class: `NodeEventTarget` 1493<!-- YAML 1494added: v14.5.0 1495--> 1496 1497* Extends: {EventTarget} 1498 1499The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` 1500that emulates a subset of the `EventEmitter` API. 1501 1502#### `nodeEventTarget.addListener(type, listener[, options])` 1503<!-- YAML 1504added: v14.5.0 1505--> 1506 1507* `type` {string} 1508* `listener` {Function|EventListener} 1509* `options` {Object} 1510 * `once` {boolean} 1511 1512* Returns: {EventTarget} this 1513 1514Node.js-specific extension to the `EventTarget` class that emulates the 1515equivalent `EventEmitter` API. The only difference between `addListener()` and 1516`addEventListener()` is that `addListener()` will return a reference to the 1517`EventTarget`. 1518 1519#### `nodeEventTarget.eventNames()` 1520<!-- YAML 1521added: v14.5.0 1522--> 1523 1524* Returns: {string[]} 1525 1526Node.js-specific extension to the `EventTarget` class that returns an array 1527of event `type` names for which event listeners are registered. 1528 1529#### `nodeEventTarget.listenerCount(type)` 1530<!-- YAML 1531added: v14.5.0 1532--> 1533 1534* `type` {string} 1535 1536* Returns: {number} 1537 1538Node.js-specific extension to the `EventTarget` class that returns the number 1539of event listeners registered for the `type`. 1540 1541#### `nodeEventTarget.off(type, listener)` 1542<!-- YAML 1543added: v14.5.0 1544--> 1545 1546* `type` {string} 1547* `listener` {Function|EventListener} 1548 1549* Returns: {EventTarget} this 1550 1551Node.js-specific alias for `eventTarget.removeListener()`. 1552 1553#### `nodeEventTarget.on(type, listener[, options])` 1554<!-- YAML 1555added: v14.5.0 1556--> 1557 1558* `type` {string} 1559* `listener` {Function|EventListener} 1560* `options` {Object} 1561 * `once` {boolean} 1562 1563* Returns: {EventTarget} this 1564 1565Node.js-specific alias for `eventTarget.addListener()`. 1566 1567#### `nodeEventTarget.once(type, listener[, options])` 1568<!-- YAML 1569added: v14.5.0 1570--> 1571 1572* `type` {string} 1573* `listener` {Function|EventListener} 1574* `options` {Object} 1575 1576* Returns: {EventTarget} this 1577 1578Node.js-specific extension to the `EventTarget` class that adds a `once` 1579listener for the given event `type`. This is equivalent to calling `on` 1580with the `once` option set to `true`. 1581 1582#### `nodeEventTarget.removeAllListeners([type])` 1583<!-- YAML 1584added: v14.5.0 1585--> 1586 1587* `type` {string} 1588 1589* Returns: {EventTarget} this 1590 1591Node.js-specific extension to the `EventTarget` class. If `type` is specified, 1592removes all registered listeners for `type`, otherwise removes all registered 1593listeners. 1594 1595#### `nodeEventTarget.removeListener(type, listener)` 1596<!-- YAML 1597added: v14.5.0 1598--> 1599 1600* `type` {string} 1601* `listener` {Function|EventListener} 1602 1603* Returns: {EventTarget} this 1604 1605Node.js-specific extension to the `EventTarget` class that removes the 1606`listener` for the given `type`. The only difference between `removeListener()` 1607and `removeEventListener()` is that `removeListener()` will return a reference 1608to the `EventTarget`. 1609 1610[WHATWG-EventTarget]: https://dom.spec.whatwg.org/#interface-eventtarget 1611[`--trace-warnings`]: cli.md#cli_trace_warnings 1612[`EventTarget` Web API]: https://dom.spec.whatwg.org/#eventtarget 1613[`EventTarget` error handling]: #events_eventtarget_error_handling 1614[`Event` Web API]: https://dom.spec.whatwg.org/#event 1615[`domain`]: domain.md 1616[`emitter.listenerCount()`]: #events_emitter_listenercount_eventname 1617[`emitter.removeListener()`]: #events_emitter_removelistener_eventname_listener 1618[`emitter.setMaxListeners(n)`]: #events_emitter_setmaxlisteners_n 1619[`events.defaultMaxListeners`]: #events_events_defaultmaxlisteners 1620[`fs.ReadStream`]: fs.md#fs_class_fs_readstream 1621[`net.Server`]: net.md#net_class_net_server 1622[`process.on('warning')`]: process.md#process_event_warning 1623[capturerejections]: #events_capture_rejections_of_promises 1624[error]: #events_error_events 1625[rejection]: #events_emitter_symbol_for_nodejs_rejection_err_eventname_args 1626[rejectionsymbol]: #events_events_capturerejectionsymbol 1627[stream]: stream.md 1628