5a5704f5158f198cf3b15435a2fd3ba29e10f59f87040b054601d116cfaf85393a32dc1148f2580818d0c333784a43bd1dd9976640031b0787701bf2997c27 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /**
  2. * Much of the Node.js core API is built around an idiomatic asynchronous
  3. * event-driven architecture in which certain kinds of objects (called "emitters")
  4. * emit named events that cause `Function` objects ("listeners") to be called.
  5. *
  6. * For instance: a `net.Server` object emits an event each time a peer
  7. * connects to it; a `fs.ReadStream` emits an event when the file is opened;
  8. * a `stream` emits an event whenever data is available to be read.
  9. *
  10. * All objects that emit events are instances of the `EventEmitter` class. These
  11. * objects expose an `eventEmitter.on()` function that allows one or more
  12. * functions to be attached to named events emitted by the object. Typically,
  13. * event names are camel-cased strings but any valid JavaScript property key
  14. * can be used.
  15. *
  16. * When the `EventEmitter` object emits an event, all of the functions attached
  17. * to that specific event are called _synchronously_. Any values returned by the
  18. * called listeners are _ignored_ and discarded.
  19. *
  20. * The following example shows a simple `EventEmitter` instance with a single
  21. * listener. The `eventEmitter.on()` method is used to register listeners, while
  22. * the `eventEmitter.emit()` method is used to trigger the event.
  23. *
  24. * ```js
  25. * import { EventEmitter } from 'node:events';
  26. *
  27. * class MyEmitter extends EventEmitter {}
  28. *
  29. * const myEmitter = new MyEmitter();
  30. * myEmitter.on('event', () => {
  31. * console.log('an event occurred!');
  32. * });
  33. * myEmitter.emit('event');
  34. * ```
  35. * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js)
  36. */
  37. declare module "events" {
  38. import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
  39. // NOTE: This class is in the docs but is **not actually exported** by Node.
  40. // If https://github.com/nodejs/node/issues/39903 gets resolved and Node
  41. // actually starts exporting the class, uncomment below.
  42. // import { EventListener, EventListenerObject } from '__dom-events';
  43. // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
  44. // interface NodeEventTarget extends EventTarget {
  45. // /**
  46. // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API.
  47. // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget.
  48. // */
  49. // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
  50. // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
  51. // eventNames(): string[];
  52. // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
  53. // listenerCount(type: string): number;
  54. // /** Node.js-specific alias for `eventTarget.removeListener()`. */
  55. // off(type: string, listener: EventListener | EventListenerObject): this;
  56. // /** Node.js-specific alias for `eventTarget.addListener()`. */
  57. // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
  58. // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */
  59. // once(type: string, listener: EventListener | EventListenerObject): this;
  60. // /**
  61. // * Node.js-specific extension to the `EventTarget` class.
  62. // * If `type` is specified, removes all registered listeners for `type`,
  63. // * otherwise removes all registered listeners.
  64. // */
  65. // removeAllListeners(type: string): this;
  66. // /**
  67. // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`.
  68. // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`.
  69. // */
  70. // removeListener(type: string, listener: EventListener | EventListenerObject): this;
  71. // }
  72. interface EventEmitterOptions {
  73. /**
  74. * Enables automatic capturing of promise rejection.
  75. */
  76. captureRejections?: boolean | undefined;
  77. }
  78. interface StaticEventEmitterOptions {
  79. /**
  80. * Can be used to cancel awaiting events.
  81. */
  82. signal?: AbortSignal | undefined;
  83. }
  84. interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions {
  85. /**
  86. * Names of events that will end the iteration.
  87. */
  88. close?: string[] | undefined;
  89. /**
  90. * The high watermark. The emitter is paused every time the size of events being buffered is higher than it.
  91. * Supported only on emitters implementing `pause()` and `resume()` methods.
  92. * @default Number.MAX_SAFE_INTEGER
  93. */
  94. highWaterMark?: number | undefined;
  95. /**
  96. * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it.
  97. * Supported only on emitters implementing `pause()` and `resume()` methods.
  98. * @default 1
  99. */
  100. lowWaterMark?: number | undefined;
  101. }
  102. interface EventEmitter<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {}
  103. type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
  104. type DefaultEventMap = [never];
  105. type AnyRest = [...args: any[]];
  106. type Args<K, T> = T extends DefaultEventMap ? AnyRest : (
  107. K extends keyof T ? T[K] : never
  108. );
  109. type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
  110. type Key2<K, T> = T extends DefaultEventMap ? string | symbol : K & keyof T;
  111. type Listener<K, T, F> = T extends DefaultEventMap ? F : (
  112. K extends keyof T ? (
  113. T[K] extends unknown[] ? (...args: T[K]) => void : never
  114. )
  115. : never
  116. );
  117. type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
  118. type Listener2<K, T> = Listener<K, T, Function>;
  119. /**
  120. * The `EventEmitter` class is defined and exposed by the `node:events` module:
  121. *
  122. * ```js
  123. * import { EventEmitter } from 'node:events';
  124. * ```
  125. *
  126. * All `EventEmitter`s emit the event `'newListener'` when new listeners are
  127. * added and `'removeListener'` when existing listeners are removed.
  128. *
  129. * It supports the following option:
  130. * @since v0.1.26
  131. */
  132. class EventEmitter<T extends EventMap<T> = DefaultEventMap> {
  133. constructor(options?: EventEmitterOptions);
  134. [EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
  135. /**
  136. * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
  137. * event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
  138. * The `Promise` will resolve with an array of all the arguments emitted to the
  139. * given event.
  140. *
  141. * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
  142. * semantics and does not listen to the `'error'` event.
  143. *
  144. * ```js
  145. * import { once, EventEmitter } from 'node:events';
  146. * import process from 'node:process';
  147. *
  148. * const ee = new EventEmitter();
  149. *
  150. * process.nextTick(() => {
  151. * ee.emit('myevent', 42);
  152. * });
  153. *
  154. * const [value] = await once(ee, 'myevent');
  155. * console.log(value);
  156. *
  157. * const err = new Error('kaboom');
  158. * process.nextTick(() => {
  159. * ee.emit('error', err);
  160. * });
  161. *
  162. * try {
  163. * await once(ee, 'myevent');
  164. * } catch (err) {
  165. * console.error('error happened', err);
  166. * }
  167. * ```
  168. *
  169. * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the
  170. * '`error'` event itself, then it is treated as any other kind of event without
  171. * special handling:
  172. *
  173. * ```js
  174. * import { EventEmitter, once } from 'node:events';
  175. *
  176. * const ee = new EventEmitter();
  177. *
  178. * once(ee, 'error')
  179. * .then(([err]) => console.log('ok', err.message))
  180. * .catch((err) => console.error('error', err.message));
  181. *
  182. * ee.emit('error', new Error('boom'));
  183. *
  184. * // Prints: ok boom
  185. * ```
  186. *
  187. * An `AbortSignal` can be used to cancel waiting for the event:
  188. *
  189. * ```js
  190. * import { EventEmitter, once } from 'node:events';
  191. *
  192. * const ee = new EventEmitter();
  193. * const ac = new AbortController();
  194. *
  195. * async function foo(emitter, event, signal) {
  196. * try {
  197. * await once(emitter, event, { signal });
  198. * console.log('event emitted!');
  199. * } catch (error) {
  200. * if (error.name === 'AbortError') {
  201. * console.error('Waiting for the event was canceled!');
  202. * } else {
  203. * console.error('There was an error', error.message);
  204. * }
  205. * }
  206. * }
  207. *
  208. * foo(ee, 'foo', ac.signal);
  209. * ac.abort(); // Abort waiting for the event
  210. * ee.emit('foo'); // Prints: Waiting for the event was canceled!
  211. * ```
  212. * @since v11.13.0, v10.16.0
  213. */
  214. static once(
  215. emitter: NodeJS.EventEmitter,
  216. eventName: string | symbol,
  217. options?: StaticEventEmitterOptions,
  218. ): Promise<any[]>;
  219. static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
  220. /**
  221. * ```js
  222. * import { on, EventEmitter } from 'node:events';
  223. * import process from 'node:process';
  224. *
  225. * const ee = new EventEmitter();
  226. *
  227. * // Emit later on
  228. * process.nextTick(() => {
  229. * ee.emit('foo', 'bar');
  230. * ee.emit('foo', 42);
  231. * });
  232. *
  233. * for await (const event of on(ee, 'foo')) {
  234. * // The execution of this inner block is synchronous and it
  235. * // processes one event at a time (even with await). Do not use
  236. * // if concurrent execution is required.
  237. * console.log(event); // prints ['bar'] [42]
  238. * }
  239. * // Unreachable here
  240. * ```
  241. *
  242. * Returns an `AsyncIterator` that iterates `eventName` events. It will throw
  243. * if the `EventEmitter` emits `'error'`. It removes all listeners when
  244. * exiting the loop. The `value` returned by each iteration is an array
  245. * composed of the emitted event arguments.
  246. *
  247. * An `AbortSignal` can be used to cancel waiting on events:
  248. *
  249. * ```js
  250. * import { on, EventEmitter } from 'node:events';
  251. * import process from 'node:process';
  252. *
  253. * const ac = new AbortController();
  254. *
  255. * (async () => {
  256. * const ee = new EventEmitter();
  257. *
  258. * // Emit later on
  259. * process.nextTick(() => {
  260. * ee.emit('foo', 'bar');
  261. * ee.emit('foo', 42);
  262. * });
  263. *
  264. * for await (const event of on(ee, 'foo', { signal: ac.signal })) {
  265. * // The execution of this inner block is synchronous and it
  266. * // processes one event at a time (even with await). Do not use
  267. * // if concurrent execution is required.
  268. * console.log(event); // prints ['bar'] [42]
  269. * }
  270. * // Unreachable here
  271. * })();
  272. *
  273. * process.nextTick(() => ac.abort());
  274. * ```
  275. *
  276. * Use the `close` option to specify an array of event names that will end the iteration:
  277. *
  278. * ```js
  279. * import { on, EventEmitter } from 'node:events';
  280. * import process from 'node:process';
  281. *
  282. * const ee = new EventEmitter();
  283. *
  284. * // Emit later on
  285. * process.nextTick(() => {
  286. * ee.emit('foo', 'bar');
  287. * ee.emit('foo', 42);
  288. * ee.emit('close');
  289. * });
  290. *
  291. * for await (const event of on(ee, 'foo', { close: ['close'] })) {
  292. * console.log(event); // prints ['bar'] [42]
  293. * }
  294. * // the loop will exit after 'close' is emitted
  295. * console.log('done'); // prints 'done'
  296. * ```
  297. * @since v13.6.0, v12.16.0
  298. * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter`
  299. */
  300. static on(
  301. emitter: NodeJS.EventEmitter,
  302. eventName: string | symbol,
  303. options?: StaticEventEmitterIteratorOptions,
  304. ): NodeJS.AsyncIterator<any[]>;
  305. static on(
  306. emitter: EventTarget,
  307. eventName: string,
  308. options?: StaticEventEmitterIteratorOptions,
  309. ): NodeJS.AsyncIterator<any[]>;
  310. /**
  311. * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`.
  312. *
  313. * ```js
  314. * import { EventEmitter, listenerCount } from 'node:events';
  315. *
  316. * const myEmitter = new EventEmitter();
  317. * myEmitter.on('event', () => {});
  318. * myEmitter.on('event', () => {});
  319. * console.log(listenerCount(myEmitter, 'event'));
  320. * // Prints: 2
  321. * ```
  322. * @since v0.9.12
  323. * @deprecated Since v3.2.0 - Use `listenerCount` instead.
  324. * @param emitter The emitter to query
  325. * @param eventName The event name
  326. */
  327. static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
  328. /**
  329. * Returns a copy of the array of listeners for the event named `eventName`.
  330. *
  331. * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
  332. * the emitter.
  333. *
  334. * For `EventTarget`s this is the only way to get the event listeners for the
  335. * event target. This is useful for debugging and diagnostic purposes.
  336. *
  337. * ```js
  338. * import { getEventListeners, EventEmitter } from 'node:events';
  339. *
  340. * {
  341. * const ee = new EventEmitter();
  342. * const listener = () => console.log('Events are fun');
  343. * ee.on('foo', listener);
  344. * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
  345. * }
  346. * {
  347. * const et = new EventTarget();
  348. * const listener = () => console.log('Events are fun');
  349. * et.addEventListener('foo', listener);
  350. * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
  351. * }
  352. * ```
  353. * @since v15.2.0, v14.17.0
  354. */
  355. static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
  356. /**
  357. * Returns the currently set max amount of listeners.
  358. *
  359. * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
  360. * the emitter.
  361. *
  362. * For `EventTarget`s this is the only way to get the max event listeners for the
  363. * event target. If the number of event handlers on a single EventTarget exceeds
  364. * the max set, the EventTarget will print a warning.
  365. *
  366. * ```js
  367. * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
  368. *
  369. * {
  370. * const ee = new EventEmitter();
  371. * console.log(getMaxListeners(ee)); // 10
  372. * setMaxListeners(11, ee);
  373. * console.log(getMaxListeners(ee)); // 11
  374. * }
  375. * {
  376. * const et = new EventTarget();
  377. * console.log(getMaxListeners(et)); // 10
  378. * setMaxListeners(11, et);
  379. * console.log(getMaxListeners(et)); // 11
  380. * }
  381. * ```
  382. * @since v19.9.0
  383. */
  384. static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number;
  385. /**
  386. * ```js
  387. * import { setMaxListeners, EventEmitter } from 'node:events';
  388. *
  389. * const target = new EventTarget();
  390. * const emitter = new EventEmitter();
  391. *
  392. * setMaxListeners(5, target, emitter);
  393. * ```
  394. * @since v15.4.0
  395. * @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
  396. * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
  397. * objects.
  398. */
  399. static setMaxListeners(n?: number, ...eventTargets: Array<EventTarget | NodeJS.EventEmitter>): void;
  400. /**
  401. * Listens once to the `abort` event on the provided `signal`.
  402. *
  403. * Listening to the `abort` event on abort signals is unsafe and may
  404. * lead to resource leaks since another third party with the signal can
  405. * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
  406. * this since it would violate the web standard. Additionally, the original
  407. * API makes it easy to forget to remove listeners.
  408. *
  409. * This API allows safely using `AbortSignal`s in Node.js APIs by solving these
  410. * two issues by listening to the event such that `stopImmediatePropagation` does
  411. * not prevent the listener from running.
  412. *
  413. * Returns a disposable so that it may be unsubscribed from more easily.
  414. *
  415. * ```js
  416. * import { addAbortListener } from 'node:events';
  417. *
  418. * function example(signal) {
  419. * let disposable;
  420. * try {
  421. * signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
  422. * disposable = addAbortListener(signal, (e) => {
  423. * // Do something when signal is aborted.
  424. * });
  425. * } finally {
  426. * disposable?.[Symbol.dispose]();
  427. * }
  428. * }
  429. * ```
  430. * @since v20.5.0
  431. * @return Disposable that removes the `abort` listener.
  432. */
  433. static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
  434. /**
  435. * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called.
  436. *
  437. * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no
  438. * regular `'error'` listener is installed.
  439. * @since v13.6.0, v12.17.0
  440. */
  441. static readonly errorMonitor: unique symbol;
  442. /**
  443. * Value: `Symbol.for('nodejs.rejection')`
  444. *
  445. * See how to write a custom `rejection handler`.
  446. * @since v13.4.0, v12.16.0
  447. */
  448. static readonly captureRejectionSymbol: unique symbol;
  449. /**
  450. * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
  451. *
  452. * Change the default `captureRejections` option on all new `EventEmitter` objects.
  453. * @since v13.4.0, v12.16.0
  454. */
  455. static captureRejections: boolean;
  456. /**
  457. * By default, a maximum of `10` listeners can be registered for any single
  458. * event. This limit can be changed for individual `EventEmitter` instances
  459. * using the `emitter.setMaxListeners(n)` method. To change the default
  460. * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property
  461. * can be used. If this value is not a positive number, a `RangeError` is thrown.
  462. *
  463. * Take caution when setting the `events.defaultMaxListeners` because the
  464. * change affects _all_ `EventEmitter` instances, including those created before
  465. * the change is made. However, calling `emitter.setMaxListeners(n)` still has
  466. * precedence over `events.defaultMaxListeners`.
  467. *
  468. * This is not a hard limit. The `EventEmitter` instance will allow
  469. * more listeners to be added but will output a trace warning to stderr indicating
  470. * that a "possible EventEmitter memory leak" has been detected. For any single
  471. * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to
  472. * temporarily avoid this warning:
  473. *
  474. * ```js
  475. * import { EventEmitter } from 'node:events';
  476. * const emitter = new EventEmitter();
  477. * emitter.setMaxListeners(emitter.getMaxListeners() + 1);
  478. * emitter.once('event', () => {
  479. * // do stuff
  480. * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
  481. * });
  482. * ```
  483. *
  484. * The `--trace-warnings` command-line flag can be used to display the
  485. * stack trace for such warnings.
  486. *
  487. * The emitted warning can be inspected with `process.on('warning')` and will
  488. * have the additional `emitter`, `type`, and `count` properties, referring to
  489. * the event emitter instance, the event's name and the number of attached
  490. * listeners, respectively.
  491. * Its `name` property is set to `'MaxListenersExceededWarning'`.
  492. * @since v0.11.2
  493. */
  494. static defaultMaxListeners: number;
  495. }
  496. import internal = require("node:events");
  497. namespace EventEmitter {
  498. // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
  499. export { internal as EventEmitter };
  500. export interface Abortable {
  501. /**
  502. * When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
  503. */
  504. signal?: AbortSignal | undefined;
  505. }
  506. export interface EventEmitterReferencingAsyncResource extends AsyncResource {
  507. readonly eventEmitter: EventEmitterAsyncResource;
  508. }
  509. export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
  510. /**
  511. * The type of async event, this is required when instantiating `EventEmitterAsyncResource`
  512. * directly rather than as a child class.
  513. * @default new.target.name if instantiated as a child class.
  514. */
  515. name?: string;
  516. }
  517. /**
  518. * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
  519. * require manual async tracking. Specifically, all events emitted by instances
  520. * of `events.EventEmitterAsyncResource` will run within its `async context`.
  521. *
  522. * ```js
  523. * import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
  524. * import { notStrictEqual, strictEqual } from 'node:assert';
  525. * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
  526. *
  527. * // Async tracking tooling will identify this as 'Q'.
  528. * const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
  529. *
  530. * // 'foo' listeners will run in the EventEmitters async context.
  531. * ee1.on('foo', () => {
  532. * strictEqual(executionAsyncId(), ee1.asyncId);
  533. * strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
  534. * });
  535. *
  536. * const ee2 = new EventEmitter();
  537. *
  538. * // 'foo' listeners on ordinary EventEmitters that do not track async
  539. * // context, however, run in the same async context as the emit().
  540. * ee2.on('foo', () => {
  541. * notStrictEqual(executionAsyncId(), ee2.asyncId);
  542. * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
  543. * });
  544. *
  545. * Promise.resolve().then(() => {
  546. * ee1.emit('foo');
  547. * ee2.emit('foo');
  548. * });
  549. * ```
  550. *
  551. * The `EventEmitterAsyncResource` class has the same methods and takes the
  552. * same options as `EventEmitter` and `AsyncResource` themselves.
  553. * @since v17.4.0, v16.14.0
  554. */
  555. export class EventEmitterAsyncResource extends EventEmitter {
  556. /**
  557. * @param options Only optional in child class.
  558. */
  559. constructor(options?: EventEmitterAsyncResourceOptions);
  560. /**
  561. * Call all `destroy` hooks. This should only ever be called once. An error will
  562. * be thrown if it is called more than once. This **must** be manually called. If
  563. * the resource is left to be collected by the GC then the `destroy` hooks will
  564. * never be called.
  565. */
  566. emitDestroy(): void;
  567. /**
  568. * The unique `asyncId` assigned to the resource.
  569. */
  570. readonly asyncId: number;
  571. /**
  572. * The same triggerAsyncId that is passed to the AsyncResource constructor.
  573. */
  574. readonly triggerAsyncId: number;
  575. /**
  576. * The returned `AsyncResource` object has an additional `eventEmitter` property
  577. * that provides a reference to this `EventEmitterAsyncResource`.
  578. */
  579. readonly asyncResource: EventEmitterReferencingAsyncResource;
  580. }
  581. }
  582. global {
  583. namespace NodeJS {
  584. interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
  585. [EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
  586. /**
  587. * Alias for `emitter.on(eventName, listener)`.
  588. * @since v0.1.26
  589. */
  590. addListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  591. /**
  592. * Adds the `listener` function to the end of the listeners array for the event
  593. * named `eventName`. No checks are made to see if the `listener` has already
  594. * been added. Multiple calls passing the same combination of `eventName` and
  595. * `listener` will result in the `listener` being added, and called, multiple times.
  596. *
  597. * ```js
  598. * server.on('connection', (stream) => {
  599. * console.log('someone connected!');
  600. * });
  601. * ```
  602. *
  603. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  604. *
  605. * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the
  606. * event listener to the beginning of the listeners array.
  607. *
  608. * ```js
  609. * import { EventEmitter } from 'node:events';
  610. * const myEE = new EventEmitter();
  611. * myEE.on('foo', () => console.log('a'));
  612. * myEE.prependListener('foo', () => console.log('b'));
  613. * myEE.emit('foo');
  614. * // Prints:
  615. * // b
  616. * // a
  617. * ```
  618. * @since v0.1.101
  619. * @param eventName The name of the event.
  620. * @param listener The callback function
  621. */
  622. on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  623. /**
  624. * Adds a **one-time** `listener` function for the event named `eventName`. The
  625. * next time `eventName` is triggered, this listener is removed and then invoked.
  626. *
  627. * ```js
  628. * server.once('connection', (stream) => {
  629. * console.log('Ah, we have our first user!');
  630. * });
  631. * ```
  632. *
  633. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  634. *
  635. * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the
  636. * event listener to the beginning of the listeners array.
  637. *
  638. * ```js
  639. * import { EventEmitter } from 'node:events';
  640. * const myEE = new EventEmitter();
  641. * myEE.once('foo', () => console.log('a'));
  642. * myEE.prependOnceListener('foo', () => console.log('b'));
  643. * myEE.emit('foo');
  644. * // Prints:
  645. * // b
  646. * // a
  647. * ```
  648. * @since v0.3.0
  649. * @param eventName The name of the event.
  650. * @param listener The callback function
  651. */
  652. once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  653. /**
  654. * Removes the specified `listener` from the listener array for the event named `eventName`.
  655. *
  656. * ```js
  657. * const callback = (stream) => {
  658. * console.log('someone connected!');
  659. * };
  660. * server.on('connection', callback);
  661. * // ...
  662. * server.removeListener('connection', callback);
  663. * ```
  664. *
  665. * `removeListener()` will remove, at most, one instance of a listener from the
  666. * listener array. If any single listener has been added multiple times to the
  667. * listener array for the specified `eventName`, then `removeListener()` must be
  668. * called multiple times to remove each instance.
  669. *
  670. * Once an event is emitted, all listeners attached to it at the
  671. * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
  672. * will not remove them from`emit()` in progress. Subsequent events behave as expected.
  673. *
  674. * ```js
  675. * import { EventEmitter } from 'node:events';
  676. * class MyEmitter extends EventEmitter {}
  677. * const myEmitter = new MyEmitter();
  678. *
  679. * const callbackA = () => {
  680. * console.log('A');
  681. * myEmitter.removeListener('event', callbackB);
  682. * };
  683. *
  684. * const callbackB = () => {
  685. * console.log('B');
  686. * };
  687. *
  688. * myEmitter.on('event', callbackA);
  689. *
  690. * myEmitter.on('event', callbackB);
  691. *
  692. * // callbackA removes listener callbackB but it will still be called.
  693. * // Internal listener array at time of emit [callbackA, callbackB]
  694. * myEmitter.emit('event');
  695. * // Prints:
  696. * // A
  697. * // B
  698. *
  699. * // callbackB is now removed.
  700. * // Internal listener array [callbackA]
  701. * myEmitter.emit('event');
  702. * // Prints:
  703. * // A
  704. * ```
  705. *
  706. * Because listeners are managed using an internal array, calling this will
  707. * change the position indices of any listener registered _after_ the listener
  708. * being removed. This will not impact the order in which listeners are called,
  709. * but it means that any copies of the listener array as returned by
  710. * the `emitter.listeners()` method will need to be recreated.
  711. *
  712. * When a single function has been added as a handler multiple times for a single
  713. * event (as in the example below), `removeListener()` will remove the most
  714. * recently added instance. In the example the `once('ping')` listener is removed:
  715. *
  716. * ```js
  717. * import { EventEmitter } from 'node:events';
  718. * const ee = new EventEmitter();
  719. *
  720. * function pong() {
  721. * console.log('pong');
  722. * }
  723. *
  724. * ee.on('ping', pong);
  725. * ee.once('ping', pong);
  726. * ee.removeListener('ping', pong);
  727. *
  728. * ee.emit('ping');
  729. * ee.emit('ping');
  730. * ```
  731. *
  732. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  733. * @since v0.1.26
  734. */
  735. removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  736. /**
  737. * Alias for `emitter.removeListener()`.
  738. * @since v10.0.0
  739. */
  740. off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  741. /**
  742. * Removes all listeners, or those of the specified `eventName`.
  743. *
  744. * It is bad practice to remove listeners added elsewhere in the code,
  745. * particularly when the `EventEmitter` instance was created by some other
  746. * component or module (e.g. sockets or file streams).
  747. *
  748. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  749. * @since v0.1.26
  750. */
  751. removeAllListeners(eventName?: Key<unknown, T>): this;
  752. /**
  753. * By default `EventEmitter`s will print a warning if more than `10` listeners are
  754. * added for a particular event. This is a useful default that helps finding
  755. * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
  756. * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners.
  757. *
  758. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  759. * @since v0.3.5
  760. */
  761. setMaxListeners(n: number): this;
  762. /**
  763. * Returns the current max listener value for the `EventEmitter` which is either
  764. * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}.
  765. * @since v1.0.0
  766. */
  767. getMaxListeners(): number;
  768. /**
  769. * Returns a copy of the array of listeners for the event named `eventName`.
  770. *
  771. * ```js
  772. * server.on('connection', (stream) => {
  773. * console.log('someone connected!');
  774. * });
  775. * console.log(util.inspect(server.listeners('connection')));
  776. * // Prints: [ [Function] ]
  777. * ```
  778. * @since v0.1.26
  779. */
  780. listeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
  781. /**
  782. * Returns a copy of the array of listeners for the event named `eventName`,
  783. * including any wrappers (such as those created by `.once()`).
  784. *
  785. * ```js
  786. * import { EventEmitter } from 'node:events';
  787. * const emitter = new EventEmitter();
  788. * emitter.once('log', () => console.log('log once'));
  789. *
  790. * // Returns a new Array with a function `onceWrapper` which has a property
  791. * // `listener` which contains the original listener bound above
  792. * const listeners = emitter.rawListeners('log');
  793. * const logFnWrapper = listeners[0];
  794. *
  795. * // Logs "log once" to the console and does not unbind the `once` event
  796. * logFnWrapper.listener();
  797. *
  798. * // Logs "log once" to the console and removes the listener
  799. * logFnWrapper();
  800. *
  801. * emitter.on('log', () => console.log('log persistently'));
  802. * // Will return a new Array with a single function bound by `.on()` above
  803. * const newListeners = emitter.rawListeners('log');
  804. *
  805. * // Logs "log persistently" twice
  806. * newListeners[0]();
  807. * emitter.emit('log');
  808. * ```
  809. * @since v9.4.0
  810. */
  811. rawListeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
  812. /**
  813. * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments
  814. * to each.
  815. *
  816. * Returns `true` if the event had listeners, `false` otherwise.
  817. *
  818. * ```js
  819. * import { EventEmitter } from 'node:events';
  820. * const myEmitter = new EventEmitter();
  821. *
  822. * // First listener
  823. * myEmitter.on('event', function firstListener() {
  824. * console.log('Helloooo! first listener');
  825. * });
  826. * // Second listener
  827. * myEmitter.on('event', function secondListener(arg1, arg2) {
  828. * console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
  829. * });
  830. * // Third listener
  831. * myEmitter.on('event', function thirdListener(...args) {
  832. * const parameters = args.join(', ');
  833. * console.log(`event with parameters ${parameters} in third listener`);
  834. * });
  835. *
  836. * console.log(myEmitter.listeners('event'));
  837. *
  838. * myEmitter.emit('event', 1, 2, 3, 4, 5);
  839. *
  840. * // Prints:
  841. * // [
  842. * // [Function: firstListener],
  843. * // [Function: secondListener],
  844. * // [Function: thirdListener]
  845. * // ]
  846. * // Helloooo! first listener
  847. * // event with parameters 1, 2 in second listener
  848. * // event with parameters 1, 2, 3, 4, 5 in third listener
  849. * ```
  850. * @since v0.1.26
  851. */
  852. emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
  853. /**
  854. * Returns the number of listeners listening for the event named `eventName`.
  855. * If `listener` is provided, it will return how many times the listener is found
  856. * in the list of the listeners of the event.
  857. * @since v3.2.0
  858. * @param eventName The name of the event being listened for
  859. * @param listener The event handler function
  860. */
  861. listenerCount<K>(eventName: Key<K, T>, listener?: Listener2<K, T>): number;
  862. /**
  863. * Adds the `listener` function to the _beginning_ of the listeners array for the
  864. * event named `eventName`. No checks are made to see if the `listener` has
  865. * already been added. Multiple calls passing the same combination of `eventName`
  866. * and `listener` will result in the `listener` being added, and called, multiple times.
  867. *
  868. * ```js
  869. * server.prependListener('connection', (stream) => {
  870. * console.log('someone connected!');
  871. * });
  872. * ```
  873. *
  874. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  875. * @since v6.0.0
  876. * @param eventName The name of the event.
  877. * @param listener The callback function
  878. */
  879. prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  880. /**
  881. * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this
  882. * listener is removed, and then invoked.
  883. *
  884. * ```js
  885. * server.prependOnceListener('connection', (stream) => {
  886. * console.log('Ah, we have our first user!');
  887. * });
  888. * ```
  889. *
  890. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  891. * @since v6.0.0
  892. * @param eventName The name of the event.
  893. * @param listener The callback function
  894. */
  895. prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  896. /**
  897. * Returns an array listing the events for which the emitter has registered
  898. * listeners. The values in the array are strings or `Symbol`s.
  899. *
  900. * ```js
  901. * import { EventEmitter } from 'node:events';
  902. *
  903. * const myEE = new EventEmitter();
  904. * myEE.on('foo', () => {});
  905. * myEE.on('bar', () => {});
  906. *
  907. * const sym = Symbol('symbol');
  908. * myEE.on(sym, () => {});
  909. *
  910. * console.log(myEE.eventNames());
  911. * // Prints: [ 'foo', 'bar', Symbol(symbol) ]
  912. * ```
  913. * @since v6.0.0
  914. */
  915. eventNames(): Array<(string | symbol) & Key2<unknown, T>>;
  916. }
  917. }
  918. }
  919. export = EventEmitter;
  920. }
  921. declare module "node:events" {
  922. import events = require("events");
  923. export = events;
  924. }