UNPKG

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