UNPKG

21 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/v16.4.2/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 static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise<any[]>;
76 static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
77 static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator<any>;
78 /** @deprecated since v4.0.0 */
79 static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
80 /**
81 * Returns a list listener for a specific emitter event name.
82 */
83 static getEventListener(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
84 /**
85 * This symbol shall be used to install a listener for only monitoring `'error'`
86 * events. Listeners installed using this symbol are called before the regular
87 * `'error'` listeners are called.
88 *
89 * Installing a listener using this symbol does not change the behavior once an
90 * `'error'` event is emitted, therefore the process will still crash if no
91 * regular `'error'` listener is installed.
92 */
93 static readonly errorMonitor: unique symbol;
94 static readonly captureRejectionSymbol: unique symbol;
95 /**
96 * Sets or gets the default captureRejection value for all emitters.
97 */
98 // TODO: These should be described using static getter/setter pairs:
99 static captureRejections: boolean;
100 static defaultMaxListeners: number;
101 }
102 import internal = require('node:events');
103 namespace EventEmitter {
104 // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
105 export { internal as EventEmitter };
106 export interface Abortable {
107 /**
108 * When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
109 */
110 signal?: AbortSignal | undefined;
111 }
112 }
113 global {
114 namespace NodeJS {
115 interface EventEmitter {
116 /**
117 * Alias for `emitter.on(eventName, listener)`.
118 * @since v0.1.26
119 */
120 addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
121 /**
122 * Adds the `listener` function to the end of the listeners array for the
123 * event named `eventName`. No checks are made to see if the `listener` has
124 * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
125 * times.
126 *
127 * ```js
128 * server.on('connection', (stream) => {
129 * console.log('someone connected!');
130 * });
131 * ```
132 *
133 * Returns a reference to the `EventEmitter`, so that calls can be chained.
134 *
135 * 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
136 * event listener to the beginning of the listeners array.
137 *
138 * ```js
139 * const myEE = new EventEmitter();
140 * myEE.on('foo', () => console.log('a'));
141 * myEE.prependListener('foo', () => console.log('b'));
142 * myEE.emit('foo');
143 * // Prints:
144 * // b
145 * // a
146 * ```
147 * @since v0.1.101
148 * @param eventName The name of the event.
149 * @param listener The callback function
150 */
151 on(eventName: string | symbol, listener: (...args: any[]) => void): this;
152 /**
153 * Adds a **one-time**`listener` function for the event named `eventName`. The
154 * next time `eventName` is triggered, this listener is removed and then invoked.
155 *
156 * ```js
157 * server.once('connection', (stream) => {
158 * console.log('Ah, we have our first user!');
159 * });
160 * ```
161 *
162 * Returns a reference to the `EventEmitter`, so that calls can be chained.
163 *
164 * 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
165 * event listener to the beginning of the listeners array.
166 *
167 * ```js
168 * const myEE = new EventEmitter();
169 * myEE.once('foo', () => console.log('a'));
170 * myEE.prependOnceListener('foo', () => console.log('b'));
171 * myEE.emit('foo');
172 * // Prints:
173 * // b
174 * // a
175 * ```
176 * @since v0.3.0
177 * @param eventName The name of the event.
178 * @param listener The callback function
179 */
180 once(eventName: string | symbol, listener: (...args: any[]) => void): this;
181 /**
182 * Removes the specified `listener` from the listener array for the event named`eventName`.
183 *
184 * ```js
185 * const callback = (stream) => {
186 * console.log('someone connected!');
187 * };
188 * server.on('connection', callback);
189 * // ...
190 * server.removeListener('connection', callback);
191 * ```
192 *
193 * `removeListener()` will remove, at most, one instance of a listener from the
194 * listener array. If any single listener has been added multiple times to the
195 * listener array for the specified `eventName`, then `removeListener()` must be
196 * called multiple times to remove each instance.
197 *
198 * Once an event is emitted, all listeners attached to it at the
199 * 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
200 * not remove them from`emit()` in progress. Subsequent events behave as expected.
201 *
202 * ```js
203 * const myEmitter = new MyEmitter();
204 *
205 * const callbackA = () => {
206 * console.log('A');
207 * myEmitter.removeListener('event', callbackB);
208 * };
209 *
210 * const callbackB = () => {
211 * console.log('B');
212 * };
213 *
214 * myEmitter.on('event', callbackA);
215 *
216 * myEmitter.on('event', callbackB);
217 *
218 * // callbackA removes listener callbackB but it will still be called.
219 * // Internal listener array at time of emit [callbackA, callbackB]
220 * myEmitter.emit('event');
221 * // Prints:
222 * // A
223 * // B
224 *
225 * // callbackB is now removed.
226 * // Internal listener array [callbackA]
227 * myEmitter.emit('event');
228 * // Prints:
229 * // A
230 * ```
231 *
232 * Because listeners are managed using an internal array, calling this will
233 * change the position indices of any listener registered _after_ the listener
234 * being removed. This will not impact the order in which listeners are called,
235 * but it means that any copies of the listener array as returned by
236 * the `emitter.listeners()` method will need to be recreated.
237 *
238 * When a single function has been added as a handler multiple times for a single
239 * event (as in the example below), `removeListener()` will remove the most
240 * recently added instance. In the example the `once('ping')`listener is removed:
241 *
242 * ```js
243 * const ee = new EventEmitter();
244 *
245 * function pong() {
246 * console.log('pong');
247 * }
248 *
249 * ee.on('ping', pong);
250 * ee.once('ping', pong);
251 * ee.removeListener('ping', pong);
252 *
253 * ee.emit('ping');
254 * ee.emit('ping');
255 * ```
256 *
257 * Returns a reference to the `EventEmitter`, so that calls can be chained.
258 * @since v0.1.26
259 */
260 removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
261 /**
262 * Alias for `emitter.removeListener()`.
263 * @since v10.0.0
264 */
265 off(eventName: string | symbol, listener: (...args: any[]) => void): this;
266 /**
267 * Removes all listeners, or those of the specified `eventName`.
268 *
269 * It is bad practice to remove listeners added elsewhere in the code,
270 * particularly when the `EventEmitter` instance was created by some other
271 * component or module (e.g. sockets or file streams).
272 *
273 * Returns a reference to the `EventEmitter`, so that calls can be chained.
274 * @since v0.1.26
275 */
276 removeAllListeners(event?: string | symbol): this;
277 /**
278 * By default `EventEmitter`s will print a warning if more than `10` listeners are
279 * added for a particular event. This is a useful default that helps finding
280 * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
281 * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners.
282 *
283 * Returns a reference to the `EventEmitter`, so that calls can be chained.
284 * @since v0.3.5
285 */
286 setMaxListeners(n: number): this;
287 /**
288 * Returns the current max listener value for the `EventEmitter` which is either
289 * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
290 * @since v1.0.0
291 */
292 getMaxListeners(): number;
293 /**
294 * Returns a copy of the array of listeners for the event named `eventName`.
295 *
296 * ```js
297 * server.on('connection', (stream) => {
298 * console.log('someone connected!');
299 * });
300 * console.log(util.inspect(server.listeners('connection')));
301 * // Prints: [ [Function] ]
302 * ```
303 * @since v0.1.26
304 */
305 listeners(eventName: string | symbol): Function[];
306 /**
307 * Returns a copy of the array of listeners for the event named `eventName`,
308 * including any wrappers (such as those created by `.once()`).
309 *
310 * ```js
311 * const emitter = new EventEmitter();
312 * emitter.once('log', () => console.log('log once'));
313 *
314 * // Returns a new Array with a function `onceWrapper` which has a property
315 * // `listener` which contains the original listener bound above
316 * const listeners = emitter.rawListeners('log');
317 * const logFnWrapper = listeners[0];
318 *
319 * // Logs "log once" to the console and does not unbind the `once` event
320 * logFnWrapper.listener();
321 *
322 * // Logs "log once" to the console and removes the listener
323 * logFnWrapper();
324 *
325 * emitter.on('log', () => console.log('log persistently'));
326 * // Will return a new Array with a single function bound by `.on()` above
327 * const newListeners = emitter.rawListeners('log');
328 *
329 * // Logs "log persistently" twice
330 * newListeners[0]();
331 * emitter.emit('log');
332 * ```
333 * @since v9.4.0
334 */
335 rawListeners(eventName: string | symbol): Function[];
336 /**
337 * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments
338 * to each.
339 *
340 * Returns `true` if the event had listeners, `false` otherwise.
341 *
342 * ```js
343 * const EventEmitter = require('events');
344 * const myEmitter = new EventEmitter();
345 *
346 * // First listener
347 * myEmitter.on('event', function firstListener() {
348 * console.log('Helloooo! first listener');
349 * });
350 * // Second listener
351 * myEmitter.on('event', function secondListener(arg1, arg2) {
352 * console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
353 * });
354 * // Third listener
355 * myEmitter.on('event', function thirdListener(...args) {
356 * const parameters = args.join(', ');
357 * console.log(`event with parameters ${parameters} in third listener`);
358 * });
359 *
360 * console.log(myEmitter.listeners('event'));
361 *
362 * myEmitter.emit('event', 1, 2, 3, 4, 5);
363 *
364 * // Prints:
365 * // [
366 * // [Function: firstListener],
367 * // [Function: secondListener],
368 * // [Function: thirdListener]
369 * // ]
370 * // Helloooo! first listener
371 * // event with parameters 1, 2 in second listener
372 * // event with parameters 1, 2, 3, 4, 5 in third listener
373 * ```
374 * @since v0.1.26
375 */
376 emit(eventName: string | symbol, ...args: any[]): boolean;
377 /**
378 * Returns the number of listeners listening to the event named `eventName`.
379 * @since v3.2.0
380 * @param eventName The name of the event being listened for
381 */
382 listenerCount(eventName: string | symbol): number;
383 /**
384 * Adds the `listener` function to the _beginning_ of the listeners array for the
385 * event named `eventName`. No checks are made to see if the `listener` has
386 * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
387 * times.
388 *
389 * ```js
390 * server.prependListener('connection', (stream) => {
391 * console.log('someone connected!');
392 * });
393 * ```
394 *
395 * Returns a reference to the `EventEmitter`, so that calls can be chained.
396 * @since v6.0.0
397 * @param eventName The name of the event.
398 * @param listener The callback function
399 */
400 prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
401 /**
402 * 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
403 * listener is removed, and then invoked.
404 *
405 * ```js
406 * server.prependOnceListener('connection', (stream) => {
407 * console.log('Ah, we have our first user!');
408 * });
409 * ```
410 *
411 * Returns a reference to the `EventEmitter`, so that calls can be chained.
412 * @since v6.0.0
413 * @param eventName The name of the event.
414 * @param listener The callback function
415 */
416 prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
417 /**
418 * Returns an array listing the events for which the emitter has registered
419 * listeners. The values in the array are strings or `Symbol`s.
420 *
421 * ```js
422 * const EventEmitter = require('events');
423 * const myEE = new EventEmitter();
424 * myEE.on('foo', () => {});
425 * myEE.on('bar', () => {});
426 *
427 * const sym = Symbol('symbol');
428 * myEE.on(sym, () => {});
429 *
430 * console.log(myEE.eventNames());
431 * // Prints: [ 'foo', 'bar', Symbol(symbol) ]
432 * ```
433 * @since v6.0.0
434 */
435 eventNames(): Array<string | symbol>;
436 }
437 }
438 }
439 export = EventEmitter;
440}
441declare module 'node:events' {
442 import events = require('events');
443 export = events;
444}