1ab969cd91c273101258da8c223a9202650b1a29462504384097afc0f5642e8fc96b1e1b126551dd6444b28e6e476be8e342f14862e2f10e3676ce8536f48a 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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/v22.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. * @experimental
  432. * @return Disposable that removes the `abort` listener.
  433. */
  434. static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
  435. /**
  436. * 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.
  437. *
  438. * 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
  439. * regular `'error'` listener is installed.
  440. * @since v13.6.0, v12.17.0
  441. */
  442. static readonly errorMonitor: unique symbol;
  443. /**
  444. * Value: `Symbol.for('nodejs.rejection')`
  445. *
  446. * See how to write a custom `rejection handler`.
  447. * @since v13.4.0, v12.16.0
  448. */
  449. static readonly captureRejectionSymbol: unique symbol;
  450. /**
  451. * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
  452. *
  453. * Change the default `captureRejections` option on all new `EventEmitter` objects.
  454. * @since v13.4.0, v12.16.0
  455. */
  456. static captureRejections: boolean;
  457. /**
  458. * By default, a maximum of `10` listeners can be registered for any single
  459. * event. This limit can be changed for individual `EventEmitter` instances
  460. * using the `emitter.setMaxListeners(n)` method. To change the default
  461. * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property
  462. * can be used. If this value is not a positive number, a `RangeError` is thrown.
  463. *
  464. * Take caution when setting the `events.defaultMaxListeners` because the
  465. * change affects _all_ `EventEmitter` instances, including those created before
  466. * the change is made. However, calling `emitter.setMaxListeners(n)` still has
  467. * precedence over `events.defaultMaxListeners`.
  468. *
  469. * This is not a hard limit. The `EventEmitter` instance will allow
  470. * more listeners to be added but will output a trace warning to stderr indicating
  471. * that a "possible EventEmitter memory leak" has been detected. For any single
  472. * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to
  473. * temporarily avoid this warning:
  474. *
  475. * ```js
  476. * import { EventEmitter } from 'node:events';
  477. * const emitter = new EventEmitter();
  478. * emitter.setMaxListeners(emitter.getMaxListeners() + 1);
  479. * emitter.once('event', () => {
  480. * // do stuff
  481. * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
  482. * });
  483. * ```
  484. *
  485. * The `--trace-warnings` command-line flag can be used to display the
  486. * stack trace for such warnings.
  487. *
  488. * The emitted warning can be inspected with `process.on('warning')` and will
  489. * have the additional `emitter`, `type`, and `count` properties, referring to
  490. * the event emitter instance, the event's name and the number of attached
  491. * listeners, respectively.
  492. * Its `name` property is set to `'MaxListenersExceededWarning'`.
  493. * @since v0.11.2
  494. */
  495. static defaultMaxListeners: number;
  496. }
  497. import internal = require("node:events");
  498. namespace EventEmitter {
  499. // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
  500. export { internal as EventEmitter };
  501. export interface Abortable {
  502. /**
  503. * When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
  504. */
  505. signal?: AbortSignal | undefined;
  506. }
  507. export interface EventEmitterReferencingAsyncResource extends AsyncResource {
  508. readonly eventEmitter: EventEmitterAsyncResource;
  509. }
  510. export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
  511. /**
  512. * The type of async event, this is required when instantiating `EventEmitterAsyncResource`
  513. * directly rather than as a child class.
  514. * @default new.target.name if instantiated as a child class.
  515. */
  516. name?: string;
  517. }
  518. /**
  519. * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
  520. * require manual async tracking. Specifically, all events emitted by instances
  521. * of `events.EventEmitterAsyncResource` will run within its `async context`.
  522. *
  523. * ```js
  524. * import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
  525. * import { notStrictEqual, strictEqual } from 'node:assert';
  526. * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
  527. *
  528. * // Async tracking tooling will identify this as 'Q'.
  529. * const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
  530. *
  531. * // 'foo' listeners will run in the EventEmitters async context.
  532. * ee1.on('foo', () => {
  533. * strictEqual(executionAsyncId(), ee1.asyncId);
  534. * strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
  535. * });
  536. *
  537. * const ee2 = new EventEmitter();
  538. *
  539. * // 'foo' listeners on ordinary EventEmitters that do not track async
  540. * // context, however, run in the same async context as the emit().
  541. * ee2.on('foo', () => {
  542. * notStrictEqual(executionAsyncId(), ee2.asyncId);
  543. * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
  544. * });
  545. *
  546. * Promise.resolve().then(() => {
  547. * ee1.emit('foo');
  548. * ee2.emit('foo');
  549. * });
  550. * ```
  551. *
  552. * The `EventEmitterAsyncResource` class has the same methods and takes the
  553. * same options as `EventEmitter` and `AsyncResource` themselves.
  554. * @since v17.4.0, v16.14.0
  555. */
  556. export class EventEmitterAsyncResource extends EventEmitter {
  557. /**
  558. * @param options Only optional in child class.
  559. */
  560. constructor(options?: EventEmitterAsyncResourceOptions);
  561. /**
  562. * Call all `destroy` hooks. This should only ever be called once. An error will
  563. * be thrown if it is called more than once. This **must** be manually called. If
  564. * the resource is left to be collected by the GC then the `destroy` hooks will
  565. * never be called.
  566. */
  567. emitDestroy(): void;
  568. /**
  569. * The unique `asyncId` assigned to the resource.
  570. */
  571. readonly asyncId: number;
  572. /**
  573. * The same triggerAsyncId that is passed to the AsyncResource constructor.
  574. */
  575. readonly triggerAsyncId: number;
  576. /**
  577. * The returned `AsyncResource` object has an additional `eventEmitter` property
  578. * that provides a reference to this `EventEmitterAsyncResource`.
  579. */
  580. readonly asyncResource: EventEmitterReferencingAsyncResource;
  581. }
  582. }
  583. global {
  584. namespace NodeJS {
  585. interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
  586. [EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
  587. /**
  588. * Alias for `emitter.on(eventName, listener)`.
  589. * @since v0.1.26
  590. */
  591. addListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  592. /**
  593. * Adds the `listener` function to the end of the listeners array for the event
  594. * named `eventName`. No checks are made to see if the `listener` has already
  595. * been added. Multiple calls passing the same combination of `eventName` and
  596. * `listener` will result in the `listener` being added, and called, multiple times.
  597. *
  598. * ```js
  599. * server.on('connection', (stream) => {
  600. * console.log('someone connected!');
  601. * });
  602. * ```
  603. *
  604. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  605. *
  606. * 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
  607. * event listener to the beginning of the listeners array.
  608. *
  609. * ```js
  610. * import { EventEmitter } from 'node:events';
  611. * const myEE = new EventEmitter();
  612. * myEE.on('foo', () => console.log('a'));
  613. * myEE.prependListener('foo', () => console.log('b'));
  614. * myEE.emit('foo');
  615. * // Prints:
  616. * // b
  617. * // a
  618. * ```
  619. * @since v0.1.101
  620. * @param eventName The name of the event.
  621. * @param listener The callback function
  622. */
  623. on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  624. /**
  625. * Adds a **one-time** `listener` function for the event named `eventName`. The
  626. * next time `eventName` is triggered, this listener is removed and then invoked.
  627. *
  628. * ```js
  629. * server.once('connection', (stream) => {
  630. * console.log('Ah, we have our first user!');
  631. * });
  632. * ```
  633. *
  634. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  635. *
  636. * 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
  637. * event listener to the beginning of the listeners array.
  638. *
  639. * ```js
  640. * import { EventEmitter } from 'node:events';
  641. * const myEE = new EventEmitter();
  642. * myEE.once('foo', () => console.log('a'));
  643. * myEE.prependOnceListener('foo', () => console.log('b'));
  644. * myEE.emit('foo');
  645. * // Prints:
  646. * // b
  647. * // a
  648. * ```
  649. * @since v0.3.0
  650. * @param eventName The name of the event.
  651. * @param listener The callback function
  652. */
  653. once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  654. /**
  655. * Removes the specified `listener` from the listener array for the event named `eventName`.
  656. *
  657. * ```js
  658. * const callback = (stream) => {
  659. * console.log('someone connected!');
  660. * };
  661. * server.on('connection', callback);
  662. * // ...
  663. * server.removeListener('connection', callback);
  664. * ```
  665. *
  666. * `removeListener()` will remove, at most, one instance of a listener from the
  667. * listener array. If any single listener has been added multiple times to the
  668. * listener array for the specified `eventName`, then `removeListener()` must be
  669. * called multiple times to remove each instance.
  670. *
  671. * Once an event is emitted, all listeners attached to it at the
  672. * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
  673. * will not remove them from`emit()` in progress. Subsequent events behave as expected.
  674. *
  675. * ```js
  676. * import { EventEmitter } from 'node:events';
  677. * class MyEmitter extends EventEmitter {}
  678. * const myEmitter = new MyEmitter();
  679. *
  680. * const callbackA = () => {
  681. * console.log('A');
  682. * myEmitter.removeListener('event', callbackB);
  683. * };
  684. *
  685. * const callbackB = () => {
  686. * console.log('B');
  687. * };
  688. *
  689. * myEmitter.on('event', callbackA);
  690. *
  691. * myEmitter.on('event', callbackB);
  692. *
  693. * // callbackA removes listener callbackB but it will still be called.
  694. * // Internal listener array at time of emit [callbackA, callbackB]
  695. * myEmitter.emit('event');
  696. * // Prints:
  697. * // A
  698. * // B
  699. *
  700. * // callbackB is now removed.
  701. * // Internal listener array [callbackA]
  702. * myEmitter.emit('event');
  703. * // Prints:
  704. * // A
  705. * ```
  706. *
  707. * Because listeners are managed using an internal array, calling this will
  708. * change the position indices of any listener registered _after_ the listener
  709. * being removed. This will not impact the order in which listeners are called,
  710. * but it means that any copies of the listener array as returned by
  711. * the `emitter.listeners()` method will need to be recreated.
  712. *
  713. * When a single function has been added as a handler multiple times for a single
  714. * event (as in the example below), `removeListener()` will remove the most
  715. * recently added instance. In the example the `once('ping')` listener is removed:
  716. *
  717. * ```js
  718. * import { EventEmitter } from 'node:events';
  719. * const ee = new EventEmitter();
  720. *
  721. * function pong() {
  722. * console.log('pong');
  723. * }
  724. *
  725. * ee.on('ping', pong);
  726. * ee.once('ping', pong);
  727. * ee.removeListener('ping', pong);
  728. *
  729. * ee.emit('ping');
  730. * ee.emit('ping');
  731. * ```
  732. *
  733. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  734. * @since v0.1.26
  735. */
  736. removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  737. /**
  738. * Alias for `emitter.removeListener()`.
  739. * @since v10.0.0
  740. */
  741. off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  742. /**
  743. * Removes all listeners, or those of the specified `eventName`.
  744. *
  745. * It is bad practice to remove listeners added elsewhere in the code,
  746. * particularly when the `EventEmitter` instance was created by some other
  747. * component or module (e.g. sockets or file streams).
  748. *
  749. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  750. * @since v0.1.26
  751. */
  752. removeAllListeners(eventName?: Key<unknown, T>): this;
  753. /**
  754. * By default `EventEmitter`s will print a warning if more than `10` listeners are
  755. * added for a particular event. This is a useful default that helps finding
  756. * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
  757. * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners.
  758. *
  759. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  760. * @since v0.3.5
  761. */
  762. setMaxListeners(n: number): this;
  763. /**
  764. * Returns the current max listener value for the `EventEmitter` which is either
  765. * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}.
  766. * @since v1.0.0
  767. */
  768. getMaxListeners(): number;
  769. /**
  770. * Returns a copy of the array of listeners for the event named `eventName`.
  771. *
  772. * ```js
  773. * server.on('connection', (stream) => {
  774. * console.log('someone connected!');
  775. * });
  776. * console.log(util.inspect(server.listeners('connection')));
  777. * // Prints: [ [Function] ]
  778. * ```
  779. * @since v0.1.26
  780. */
  781. listeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
  782. /**
  783. * Returns a copy of the array of listeners for the event named `eventName`,
  784. * including any wrappers (such as those created by `.once()`).
  785. *
  786. * ```js
  787. * import { EventEmitter } from 'node:events';
  788. * const emitter = new EventEmitter();
  789. * emitter.once('log', () => console.log('log once'));
  790. *
  791. * // Returns a new Array with a function `onceWrapper` which has a property
  792. * // `listener` which contains the original listener bound above
  793. * const listeners = emitter.rawListeners('log');
  794. * const logFnWrapper = listeners[0];
  795. *
  796. * // Logs "log once" to the console and does not unbind the `once` event
  797. * logFnWrapper.listener();
  798. *
  799. * // Logs "log once" to the console and removes the listener
  800. * logFnWrapper();
  801. *
  802. * emitter.on('log', () => console.log('log persistently'));
  803. * // Will return a new Array with a single function bound by `.on()` above
  804. * const newListeners = emitter.rawListeners('log');
  805. *
  806. * // Logs "log persistently" twice
  807. * newListeners[0]();
  808. * emitter.emit('log');
  809. * ```
  810. * @since v9.4.0
  811. */
  812. rawListeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
  813. /**
  814. * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments
  815. * to each.
  816. *
  817. * Returns `true` if the event had listeners, `false` otherwise.
  818. *
  819. * ```js
  820. * import { EventEmitter } from 'node:events';
  821. * const myEmitter = new EventEmitter();
  822. *
  823. * // First listener
  824. * myEmitter.on('event', function firstListener() {
  825. * console.log('Helloooo! first listener');
  826. * });
  827. * // Second listener
  828. * myEmitter.on('event', function secondListener(arg1, arg2) {
  829. * console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
  830. * });
  831. * // Third listener
  832. * myEmitter.on('event', function thirdListener(...args) {
  833. * const parameters = args.join(', ');
  834. * console.log(`event with parameters ${parameters} in third listener`);
  835. * });
  836. *
  837. * console.log(myEmitter.listeners('event'));
  838. *
  839. * myEmitter.emit('event', 1, 2, 3, 4, 5);
  840. *
  841. * // Prints:
  842. * // [
  843. * // [Function: firstListener],
  844. * // [Function: secondListener],
  845. * // [Function: thirdListener]
  846. * // ]
  847. * // Helloooo! first listener
  848. * // event with parameters 1, 2 in second listener
  849. * // event with parameters 1, 2, 3, 4, 5 in third listener
  850. * ```
  851. * @since v0.1.26
  852. */
  853. emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
  854. /**
  855. * Returns the number of listeners listening for the event named `eventName`.
  856. * If `listener` is provided, it will return how many times the listener is found
  857. * in the list of the listeners of the event.
  858. * @since v3.2.0
  859. * @param eventName The name of the event being listened for
  860. * @param listener The event handler function
  861. */
  862. listenerCount<K>(eventName: Key<K, T>, listener?: Listener2<K, T>): number;
  863. /**
  864. * Adds the `listener` function to the _beginning_ of the listeners array for the
  865. * event named `eventName`. No checks are made to see if the `listener` has
  866. * already been added. Multiple calls passing the same combination of `eventName`
  867. * and `listener` will result in the `listener` being added, and called, multiple times.
  868. *
  869. * ```js
  870. * server.prependListener('connection', (stream) => {
  871. * console.log('someone connected!');
  872. * });
  873. * ```
  874. *
  875. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  876. * @since v6.0.0
  877. * @param eventName The name of the event.
  878. * @param listener The callback function
  879. */
  880. prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  881. /**
  882. * 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
  883. * listener is removed, and then invoked.
  884. *
  885. * ```js
  886. * server.prependOnceListener('connection', (stream) => {
  887. * console.log('Ah, we have our first user!');
  888. * });
  889. * ```
  890. *
  891. * Returns a reference to the `EventEmitter`, so that calls can be chained.
  892. * @since v6.0.0
  893. * @param eventName The name of the event.
  894. * @param listener The callback function
  895. */
  896. prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
  897. /**
  898. * Returns an array listing the events for which the emitter has registered
  899. * listeners. The values in the array are strings or `Symbol`s.
  900. *
  901. * ```js
  902. * import { EventEmitter } from 'node:events';
  903. *
  904. * const myEE = new EventEmitter();
  905. * myEE.on('foo', () => {});
  906. * myEE.on('bar', () => {});
  907. *
  908. * const sym = Symbol('symbol');
  909. * myEE.on(sym, () => {});
  910. *
  911. * console.log(myEE.eventNames());
  912. * // Prints: [ 'foo', 'bar', Symbol(symbol) ]
  913. * ```
  914. * @since v6.0.0
  915. */
  916. eventNames(): Array<(string | symbol) & Key2<unknown, T>>;
  917. }
  918. }
  919. }
  920. export = EventEmitter;
  921. }
  922. declare module "node:events" {
  923. import events = require("events");
  924. export = events;
  925. }