UNPKG

29.1 kBTypeScriptView Raw
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 * const EventEmitter = require('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/v17.0.0/lib/events.js)
36 */
37declare module 'events' {
38 interface EventEmitterOptions {
39 /**
40 * Enables automatic capturing of promise rejection.
41 */
42 captureRejections?: boolean | undefined;
43 }
44 interface NodeEventTarget {
45 once(eventName: string | symbol, listener: (...args: any[]) => void): this;
46 }
47 interface DOMEventTarget {
48 addEventListener(
49 eventName: string,
50 listener: (...args: any[]) => void,
51 opts?: {
52 once: boolean;
53 },
54 ): any;
55 }
56 interface StaticEventEmitterOptions {
57 signal?: AbortSignal | undefined;
58 }
59 interface EventEmitter extends NodeJS.EventEmitter {}
60 /**
61 * The `EventEmitter` class is defined and exposed by the `events` module:
62 *
63 * ```js
64 * const EventEmitter = require('events');
65 * ```
66 *
67 * All `EventEmitter`s emit the event `'newListener'` when new listeners are
68 * added and `'removeListener'` when existing listeners are removed.
69 *
70 * It supports the following option:
71 * @since v0.1.26
72 */
73 class EventEmitter {
74 constructor(options?: EventEmitterOptions);
75 /**
76 * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
77 * event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
78 * The `Promise` will resolve with an array of all the arguments emitted to the
79 * given event.
80 *
81 * 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
82 * semantics and does not listen to the `'error'` event.
83 *
84 * ```js
85 * const { once, EventEmitter } = require('events');
86 *
87 * async function run() {
88 * const ee = new EventEmitter();
89 *
90 * process.nextTick(() => {
91 * ee.emit('myevent', 42);
92 * });
93 *
94 * const [value] = await once(ee, 'myevent');
95 * console.log(value);
96 *
97 * const err = new Error('kaboom');
98 * process.nextTick(() => {
99 * ee.emit('error', err);
100 * });
101 *
102 * try {
103 * await once(ee, 'myevent');
104 * } catch (err) {
105 * console.log('error happened', err);
106 * }
107 * }
108 *
109 * run();
110 * ```
111 *
112 * 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
113 * '`error'` event itself, then it is treated as any other kind of event without
114 * special handling:
115 *
116 * ```js
117 * const { EventEmitter, once } = require('events');
118 *
119 * const ee = new EventEmitter();
120 *
121 * once(ee, 'error')
122 * .then(([err]) => console.log('ok', err.message))
123 * .catch((err) => console.log('error', err.message));
124 *
125 * ee.emit('error', new Error('boom'));
126 *
127 * // Prints: ok boom
128 * ```
129 *
130 * An `AbortSignal` can be used to cancel waiting for the event:
131 *
132 * ```js
133 * const { EventEmitter, once } = require('events');
134 *
135 * const ee = new EventEmitter();
136 * const ac = new AbortController();
137 *
138 * async function foo(emitter, event, signal) {
139 * try {
140 * await once(emitter, event, { signal });
141 * console.log('event emitted!');
142 * } catch (error) {
143 * if (error.name === 'AbortError') {
144 * console.error('Waiting for the event was canceled!');
145 * } else {
146 * console.error('There was an error', error.message);
147 * }
148 * }
149 * }
150 *
151 * foo(ee, 'foo', ac.signal);
152 * ac.abort(); // Abort waiting for the event
153 * ee.emit('foo'); // Prints: Waiting for the event was canceled!
154 * ```
155 * @since v11.13.0, v10.16.0
156 */
157 static once(
158 emitter: NodeEventTarget,
159 eventName: string | symbol,
160 options?: StaticEventEmitterOptions,
161 ): Promise<any[]>;
162 static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
163 /**
164 * ```js
165 * const { on, EventEmitter } = require('events');
166 *
167 * (async () => {
168 * const ee = new EventEmitter();
169 *
170 * // Emit later on
171 * process.nextTick(() => {
172 * ee.emit('foo', 'bar');
173 * ee.emit('foo', 42);
174 * });
175 *
176 * for await (const event of on(ee, 'foo')) {
177 * // The execution of this inner block is synchronous and it
178 * // processes one event at a time (even with await). Do not use
179 * // if concurrent execution is required.
180 * console.log(event); // prints ['bar'] [42]
181 * }
182 * // Unreachable here
183 * })();
184 * ```
185 *
186 * Returns an `AsyncIterator` that iterates `eventName` events. It will throw
187 * if the `EventEmitter` emits `'error'`. It removes all listeners when
188 * exiting the loop. The `value` returned by each iteration is an array
189 * composed of the emitted event arguments.
190 *
191 * An `AbortSignal` can be used to cancel waiting on events:
192 *
193 * ```js
194 * const { on, EventEmitter } = require('events');
195 * const ac = new AbortController();
196 *
197 * (async () => {
198 * const ee = new EventEmitter();
199 *
200 * // Emit later on
201 * process.nextTick(() => {
202 * ee.emit('foo', 'bar');
203 * ee.emit('foo', 42);
204 * });
205 *
206 * for await (const event of on(ee, 'foo', { signal: ac.signal })) {
207 * // The execution of this inner block is synchronous and it
208 * // processes one event at a time (even with await). Do not use
209 * // if concurrent execution is required.
210 * console.log(event); // prints ['bar'] [42]
211 * }
212 * // Unreachable here
213 * })();
214 *
215 * process.nextTick(() => ac.abort());
216 * ```
217 * @since v13.6.0, v12.16.0
218 * @param eventName The name of the event being listened for
219 * @return that iterates `eventName` events emitted by the `emitter`
220 */
221 static on(
222 emitter: NodeJS.EventEmitter,
223 eventName: string,
224 options?: StaticEventEmitterOptions,
225 ): AsyncIterableIterator<any>;
226 /**
227 * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`.
228 *
229 * ```js
230 * const { EventEmitter, listenerCount } = require('events');
231 * const myEmitter = new EventEmitter();
232 * myEmitter.on('event', () => {});
233 * myEmitter.on('event', () => {});
234 * console.log(listenerCount(myEmitter, 'event'));
235 * // Prints: 2
236 * ```
237 * @since v0.9.12
238 * @deprecated Since v3.2.0 - Use `listenerCount` instead.
239 * @param emitter The emitter to query
240 * @param eventName The event name
241 */
242 static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
243 /**
244 * Returns a copy of the array of listeners for the event named `eventName`.
245 *
246 * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
247 * the emitter.
248 *
249 * For `EventTarget`s this is the only way to get the event listeners for the
250 * event target. This is useful for debugging and diagnostic purposes.
251 *
252 * ```js
253 * const { getEventListeners, EventEmitter } = require('events');
254 *
255 * {
256 * const ee = new EventEmitter();
257 * const listener = () => console.log('Events are fun');
258 * ee.on('foo', listener);
259 * getEventListeners(ee, 'foo'); // [listener]
260 * }
261 * {
262 * const et = new EventTarget();
263 * const listener = () => console.log('Events are fun');
264 * et.addEventListener('foo', listener);
265 * getEventListeners(et, 'foo'); // [listener]
266 * }
267 * ```
268 * @since v15.2.0, v14.17.0
269 */
270 static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
271 /**
272 * By default `EventEmitter`s will print a warning if more than `10` listeners are
273 * added for a particular event. This is a useful default that helps finding
274 * memory leaks. The `EventEmitter.setMaxListeners()` method allows the default limit to be
275 * modified (if eventTargets is empty) or modify the limit specified in every `EventTarget` | `EventEmitter` passed as arguments.
276 * The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners.
277 *
278 * ```js
279 * EventEmitter.setMaxListeners(20);
280 * // Equivalent to
281 * EventEmitter.defaultMaxListeners = 20;
282 *
283 * const eventTarget = new EventTarget();
284 * // Only way to increase limit for `EventTarget` instances
285 * // as these doesn't expose its own `setMaxListeners` method
286 * EventEmitter.setMaxListeners(20, eventTarget);
287 * ```
288 * @since v15.3.0, v14.17.0
289 */
290 static setMaxListeners(n?: number, ...eventTargets: Array<DOMEventTarget | NodeJS.EventEmitter>): void;
291 /**
292 * This symbol shall be used to install a listener for only monitoring `'error'`
293 * events. Listeners installed using this symbol are called before the regular
294 * `'error'` listeners are called.
295 *
296 * Installing a listener using this symbol does not change the behavior once an
297 * `'error'` event is emitted, therefore the process will still crash if no
298 * regular `'error'` listener is installed.
299 */
300 static readonly errorMonitor: unique symbol;
301 static readonly captureRejectionSymbol: unique symbol;
302 /**
303 * Sets or gets the default captureRejection value for all emitters.
304 */
305 // TODO: These should be described using static getter/setter pairs:
306 static captureRejections: boolean;
307 static defaultMaxListeners: number;
308 }
309 import internal = require('node:events');
310 namespace EventEmitter {
311 // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
312 export { internal as EventEmitter };
313 export interface Abortable {
314 /**
315 * When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
316 */
317 signal?: AbortSignal | undefined;
318 }
319 }
320 global {
321 namespace NodeJS {
322 interface EventEmitter {
323 /**
324 * Alias for `emitter.on(eventName, listener)`.
325 * @since v0.1.26
326 */
327 addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
328 /**
329 * Adds the `listener` function to the end of the listeners array for the
330 * event named `eventName`. No checks are made to see if the `listener` has
331 * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
332 * times.
333 *
334 * ```js
335 * server.on('connection', (stream) => {
336 * console.log('someone connected!');
337 * });
338 * ```
339 *
340 * Returns a reference to the `EventEmitter`, so that calls can be chained.
341 *
342 * 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
343 * event listener to the beginning of the listeners array.
344 *
345 * ```js
346 * const myEE = new EventEmitter();
347 * myEE.on('foo', () => console.log('a'));
348 * myEE.prependListener('foo', () => console.log('b'));
349 * myEE.emit('foo');
350 * // Prints:
351 * // b
352 * // a
353 * ```
354 * @since v0.1.101
355 * @param eventName The name of the event.
356 * @param listener The callback function
357 */
358 on(eventName: string | symbol, listener: (...args: any[]) => void): this;
359 /**
360 * Adds a **one-time**`listener` function for the event named `eventName`. The
361 * next time `eventName` is triggered, this listener is removed and then invoked.
362 *
363 * ```js
364 * server.once('connection', (stream) => {
365 * console.log('Ah, we have our first user!');
366 * });
367 * ```
368 *
369 * Returns a reference to the `EventEmitter`, so that calls can be chained.
370 *
371 * 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
372 * event listener to the beginning of the listeners array.
373 *
374 * ```js
375 * const myEE = new EventEmitter();
376 * myEE.once('foo', () => console.log('a'));
377 * myEE.prependOnceListener('foo', () => console.log('b'));
378 * myEE.emit('foo');
379 * // Prints:
380 * // b
381 * // a
382 * ```
383 * @since v0.3.0
384 * @param eventName The name of the event.
385 * @param listener The callback function
386 */
387 once(eventName: string | symbol, listener: (...args: any[]) => void): this;
388 /**
389 * Removes the specified `listener` from the listener array for the event named`eventName`.
390 *
391 * ```js
392 * const callback = (stream) => {
393 * console.log('someone connected!');
394 * };
395 * server.on('connection', callback);
396 * // ...
397 * server.removeListener('connection', callback);
398 * ```
399 *
400 * `removeListener()` will remove, at most, one instance of a listener from the
401 * listener array. If any single listener has been added multiple times to the
402 * listener array for the specified `eventName`, then `removeListener()` must be
403 * called multiple times to remove each instance.
404 *
405 * Once an event is emitted, all listeners attached to it at the
406 * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will
407 * not remove them from`emit()` in progress. Subsequent events behave as expected.
408 *
409 * ```js
410 * const myEmitter = new MyEmitter();
411 *
412 * const callbackA = () => {
413 * console.log('A');
414 * myEmitter.removeListener('event', callbackB);
415 * };
416 *
417 * const callbackB = () => {
418 * console.log('B');
419 * };
420 *
421 * myEmitter.on('event', callbackA);
422 *
423 * myEmitter.on('event', callbackB);
424 *
425 * // callbackA removes listener callbackB but it will still be called.
426 * // Internal listener array at time of emit [callbackA, callbackB]
427 * myEmitter.emit('event');
428 * // Prints:
429 * // A
430 * // B
431 *
432 * // callbackB is now removed.
433 * // Internal listener array [callbackA]
434 * myEmitter.emit('event');
435 * // Prints:
436 * // A
437 * ```
438 *
439 * Because listeners are managed using an internal array, calling this will
440 * change the position indices of any listener registered _after_ the listener
441 * being removed. This will not impact the order in which listeners are called,
442 * but it means that any copies of the listener array as returned by
443 * the `emitter.listeners()` method will need to be recreated.
444 *
445 * When a single function has been added as a handler multiple times for a single
446 * event (as in the example below), `removeListener()` will remove the most
447 * recently added instance. In the example the `once('ping')`listener is removed:
448 *
449 * ```js
450 * const ee = new EventEmitter();
451 *
452 * function pong() {
453 * console.log('pong');
454 * }
455 *
456 * ee.on('ping', pong);
457 * ee.once('ping', pong);
458 * ee.removeListener('ping', pong);
459 *
460 * ee.emit('ping');
461 * ee.emit('ping');
462 * ```
463 *
464 * Returns a reference to the `EventEmitter`, so that calls can be chained.
465 * @since v0.1.26
466 */
467 removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
468 /**
469 * Alias for `emitter.removeListener()`.
470 * @since v10.0.0
471 */
472 off(eventName: string | symbol, listener: (...args: any[]) => void): this;
473 /**
474 * Removes all listeners, or those of the specified `eventName`.
475 *
476 * It is bad practice to remove listeners added elsewhere in the code,
477 * particularly when the `EventEmitter` instance was created by some other
478 * component or module (e.g. sockets or file streams).
479 *
480 * Returns a reference to the `EventEmitter`, so that calls can be chained.
481 * @since v0.1.26
482 */
483 removeAllListeners(event?: string | symbol): this;
484 /**
485 * By default `EventEmitter`s will print a warning if more than `10` listeners are
486 * added for a particular event. This is a useful default that helps finding
487 * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
488 * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners.
489 *
490 * Returns a reference to the `EventEmitter`, so that calls can be chained.
491 * @since v0.3.5
492 */
493 setMaxListeners(n: number): this;
494 /**
495 * Returns the current max listener value for the `EventEmitter` which is either
496 * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
497 * @since v1.0.0
498 */
499 getMaxListeners(): number;
500 /**
501 * Returns a copy of the array of listeners for the event named `eventName`.
502 *
503 * ```js
504 * server.on('connection', (stream) => {
505 * console.log('someone connected!');
506 * });
507 * console.log(util.inspect(server.listeners('connection')));
508 * // Prints: [ [Function] ]
509 * ```
510 * @since v0.1.26
511 */
512 listeners(eventName: string | symbol): Function[];
513 /**
514 * Returns a copy of the array of listeners for the event named `eventName`,
515 * including any wrappers (such as those created by `.once()`).
516 *
517 * ```js
518 * const emitter = new EventEmitter();
519 * emitter.once('log', () => console.log('log once'));
520 *
521 * // Returns a new Array with a function `onceWrapper` which has a property
522 * // `listener` which contains the original listener bound above
523 * const listeners = emitter.rawListeners('log');
524 * const logFnWrapper = listeners[0];
525 *
526 * // Logs "log once" to the console and does not unbind the `once` event
527 * logFnWrapper.listener();
528 *
529 * // Logs "log once" to the console and removes the listener
530 * logFnWrapper();
531 *
532 * emitter.on('log', () => console.log('log persistently'));
533 * // Will return a new Array with a single function bound by `.on()` above
534 * const newListeners = emitter.rawListeners('log');
535 *
536 * // Logs "log persistently" twice
537 * newListeners[0]();
538 * emitter.emit('log');
539 * ```
540 * @since v9.4.0
541 */
542 rawListeners(eventName: string | symbol): Function[];
543 /**
544 * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments
545 * to each.
546 *
547 * Returns `true` if the event had listeners, `false` otherwise.
548 *
549 * ```js
550 * const EventEmitter = require('events');
551 * const myEmitter = new EventEmitter();
552 *
553 * // First listener
554 * myEmitter.on('event', function firstListener() {
555 * console.log('Helloooo! first listener');
556 * });
557 * // Second listener
558 * myEmitter.on('event', function secondListener(arg1, arg2) {
559 * console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
560 * });
561 * // Third listener
562 * myEmitter.on('event', function thirdListener(...args) {
563 * const parameters = args.join(', ');
564 * console.log(`event with parameters ${parameters} in third listener`);
565 * });
566 *
567 * console.log(myEmitter.listeners('event'));
568 *
569 * myEmitter.emit('event', 1, 2, 3, 4, 5);
570 *
571 * // Prints:
572 * // [
573 * // [Function: firstListener],
574 * // [Function: secondListener],
575 * // [Function: thirdListener]
576 * // ]
577 * // Helloooo! first listener
578 * // event with parameters 1, 2 in second listener
579 * // event with parameters 1, 2, 3, 4, 5 in third listener
580 * ```
581 * @since v0.1.26
582 */
583 emit(eventName: string | symbol, ...args: any[]): boolean;
584 /**
585 * Returns the number of listeners listening to the event named `eventName`.
586 * @since v3.2.0
587 * @param eventName The name of the event being listened for
588 */
589 listenerCount(eventName: string | symbol): number;
590 /**
591 * Adds the `listener` function to the _beginning_ of the listeners array for the
592 * event named `eventName`. No checks are made to see if the `listener` has
593 * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
594 * times.
595 *
596 * ```js
597 * server.prependListener('connection', (stream) => {
598 * console.log('someone connected!');
599 * });
600 * ```
601 *
602 * Returns a reference to the `EventEmitter`, so that calls can be chained.
603 * @since v6.0.0
604 * @param eventName The name of the event.
605 * @param listener The callback function
606 */
607 prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
608 /**
609 * 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
610 * listener is removed, and then invoked.
611 *
612 * ```js
613 * server.prependOnceListener('connection', (stream) => {
614 * console.log('Ah, we have our first user!');
615 * });
616 * ```
617 *
618 * Returns a reference to the `EventEmitter`, so that calls can be chained.
619 * @since v6.0.0
620 * @param eventName The name of the event.
621 * @param listener The callback function
622 */
623 prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
624 /**
625 * Returns an array listing the events for which the emitter has registered
626 * listeners. The values in the array are strings or `Symbol`s.
627 *
628 * ```js
629 * const EventEmitter = require('events');
630 * const myEE = new EventEmitter();
631 * myEE.on('foo', () => {});
632 * myEE.on('bar', () => {});
633 *
634 * const sym = Symbol('symbol');
635 * myEE.on(sym, () => {});
636 *
637 * console.log(myEE.eventNames());
638 * // Prints: [ 'foo', 'bar', Symbol(symbol) ]
639 * ```
640 * @since v6.0.0
641 */
642 eventNames(): Array<string | symbol>;
643 }
644 }
645 }
646 export = EventEmitter;
647}
648declare module 'node:events' {
649 import events = require('events');
650 export = events;
651}
652
\No newline at end of file