Hierarchy

  • Minipass<string>
    • MarkdownStream

Constructors

Properties

[ABORTED]: boolean
[ASYNC]: boolean
[BUFFERLENGTH]: number
[BUFFER]: string[]
[CLOSED]: boolean
[DATALISTENERS]: number
[DECODER]: null | SD
[DESTROYED]: boolean
[DISCARDED]: boolean
[EMITTED_END]: boolean
[EMITTED_ERROR]: unknown
[EMITTING_END]: boolean
[ENCODING]: null | BufferEncoding
[EOF]: boolean
[FLOWING]: boolean
[OBJECTMODE]: boolean
[PAUSED]: boolean
[PIPES]: Pipe<string>[]
[SIGNAL]?: AbortSignal
parser: Parser = ...
readable: boolean

true if the stream can be read

writable: boolean

true if the stream can be written

captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

v13.4.0, v12.16.0

captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

v13.4.0, v12.16.0

defaultMaxListeners: number

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for allEventEmitter instances, the events.defaultMaxListeners property can be used. If this value is not a positive number, a RangeError is thrown.

Take caution when setting the events.defaultMaxListeners because the change affects all EventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any single EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to temporarily avoid this warning:

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Its name property is set to 'MaxListenersExceededWarning'.

v0.11.2

errorMonitor: typeof errorMonitor

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.

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 regular 'error' listener is installed.

v13.6.0, v12.17.0

Accessors

  • get aborted(): boolean
  • True if the stream has been aborted.

    Returns boolean

  • set aborted(_): void
  • No-op setter. Stream aborted status is set via the AbortSignal provided in the constructor options.

    Parameters

    • _: boolean

    Returns void

  • get async(): boolean
  • true if this is an async stream

    Returns boolean

  • set async(a): void
  • Set to true to make this stream async.

    Once set, it cannot be unset, as this would potentially cause incorrect behavior. Ie, a sync stream can be made async, but an async stream cannot be safely made sync.

    Parameters

    • a: boolean

    Returns void

  • get bufferLength(): number
  • The amount of data stored in the buffer waiting to be read.

    For Buffer strings, this will be the total byte length. For string encoding streams, this will be the string character length, according to JavaScript's string.length logic. For objectMode streams, this is a count of the items waiting to be emitted.

    Returns number

  • get destroyed(): boolean
  • true if the stream has been forcibly destroyed

    Returns boolean

  • get emittedEnd(): boolean
  • true if the 'end' event has been emitted

    Returns boolean

  • get encoding(): null | BufferEncoding
  • The BufferEncoding currently in use, or null

    Returns null | BufferEncoding

  • set encoding(_enc): void
  • Parameters

    • _enc: null | BufferEncoding

    Returns void

    • This is a read only property
  • get flowing(): boolean
  • true if the stream is currently in a flowing state, meaning that any writes will be immediately emitted.

    Returns boolean

  • get objectMode(): boolean
  • True if this is an objectMode stream

    Returns boolean

  • set objectMode(_om): void
  • Parameters

    • _om: boolean

    Returns void

    • This is a read-only property
  • get paused(): boolean
  • true if the stream is currently in a paused state

    Returns boolean

  • get isStream(): ((s: any) => s is
        | Minipass<any, any, any>
        | WriteStream
        | ReadStream
        | ReadStream & {
            fd: number;
        }
        | EventEmitter<DefaultEventMap> & {
            pause(): any;
            pipe(...destArgs: any[]): any;
            resume(): any;
        }
        | WriteStream & {
            fd: number;
        }
        | EventEmitter<DefaultEventMap> & {
            end(): any;
            write(chunk: any, ...args: any[]): any;
        })
  • Alias for isStream

    Former export location, maintained for backwards compatibility.

    Returns ((s: any) => s is
        | Minipass<any, any, any>
        | WriteStream
        | ReadStream
        | ReadStream & {
            fd: number;
        }
        | EventEmitter<DefaultEventMap> & {
            pause(): any;
            pipe(...destArgs: any[]): any;
            resume(): any;
        }
        | WriteStream & {
            fd: number;
        }
        | EventEmitter<DefaultEventMap> & {
            end(): any;
            write(chunk: any, ...args: any[]): any;
        })

      • (s): s is
            | Minipass<any, any, any>
            | WriteStream
            | ReadStream
            | ReadStream & {
                fd: number;
            }
            | EventEmitter<DefaultEventMap> & {
                pause(): any;
                pipe(...destArgs: any[]): any;
                resume(): any;
            }
            | WriteStream & {
                fd: number;
            }
            | EventEmitter<DefaultEventMap> & {
                end(): any;
                write(chunk: any, ...args: any[]): any;
            }
      • Parameters

        • s: any

        Returns s is
            | Minipass<any, any, any>
            | WriteStream
            | ReadStream
            | ReadStream & {
                fd: number;
            }
            | EventEmitter<DefaultEventMap> & {
                pause(): any;
                pipe(...destArgs: any[]): any;
                resume(): any;
            }
            | WriteStream & {
                fd: number;
            }
            | EventEmitter<DefaultEventMap> & {
                end(): any;
                write(chunk: any, ...args: any[]): any;
            }

Methods

  • Returns void

  • Parameters

    • chunk: string

    Returns void

  • Returns string

  • Parameters

    • data: string

    Returns boolean

  • Returns boolean

  • Returns boolean

  • Parameters

    • chunk: string

    Returns boolean

  • Parameters

    • OptionalnoDrain: boolean

    Returns void

  • Returns void

  • Parameters

    • n: null | number
    • chunk: string

    Returns string

  • Returns void

  • Asynchronous for await of iteration.

    This will continue emitting all chunks until the stream terminates.

    Returns AsyncGenerator<string, void, void>

  • Type Parameters

    • K

    Parameters

    • error: Error
    • event: string | symbol
    • Rest...args: AnyRest

    Returns void

  • Synchronous for of iteration.

    The iteration will terminate when the internal buffer runs out, even if the stream has not yet terminated.

    Returns Generator<string, void, void>

  • Alias for Minipass#on

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    • ev: Event
    • handler: ((...args: Events<string>[Event]) => any)
        • (...args): any
        • Parameters

          • Rest...args: Events<string>[Event]

          Returns any

    Returns this

  • Return a Promise that resolves to an array of all emitted data once the stream ends.

    Returns Promise<string[] & {
        dataLength: number;
    }>

  • Return a Promise that resolves to the concatenation of all emitted data once the stream ends.

    Not allowed on objectMode streams.

    Returns Promise<string>

  • Destroy a stream, preventing it from being used for any further purpose.

    If the stream has a close() method, then it will be called on destruction.

    After destruction, any attempt to write data, read data, or emit most events will be ignored.

    If an error argument is provided, then it will be emitted in an 'error' event.

    Parameters

    • Optionaler: unknown

    Returns this

  • Mostly identical to EventEmitter.emit, with the following behavior differences to prevent data loss and unnecessary hangs:

    If the stream has been destroyed, and the event is something other than 'close' or 'error', then false is returned and no handlers are called.

    If the event is 'end', and has already been emitted, then the event is ignored. If the stream is in a paused or non-flowing state, then the event will be deferred until data flow resumes. If the stream is async, then handlers will be called on the next tick rather than immediately.

    If the event is 'close', and 'end' has not yet been emitted, then the event will be deferred until after 'end' is emitted.

    If the event is 'error', and an AbortSignal was provided for the stream, and there are no listeners, then the event is ignored, matching the behavior of node core streams in the presense of an AbortSignal.

    If the event is 'finish' or 'prefinish', then all listeners will be removed after emitting the event, to prevent double-firing.

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    Returns boolean

  • End the stream, optionally providing a final write.

    See Minipass#write for argument descriptions

    Parameters

    • Optionalcb: (() => void)
        • (): void
        • Returns void

    Returns this

  • End the stream, optionally providing a final write.

    See Minipass#write for argument descriptions

    Parameters

    • chunk: ContiguousData
    • Optionalcb: (() => void)
        • (): void
        • Returns void

    Returns this

  • End the stream, optionally providing a final write.

    See Minipass#write for argument descriptions

    Parameters

    • chunk: ContiguousData
    • Optionalencoding: Encoding
    • Optionalcb: (() => void)
        • (): void
        • Returns void

    Returns this

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    import { EventEmitter } from 'node:events';

    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ]

    Returns (string | symbol)[]

    v6.0.0

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Returns number

    v1.0.0

  • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optionallistener: Function

      The event handler function

    Returns number

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v0.1.26

  • Mostly identical to EventEmitter.off

    If a 'data' event handler is removed, and it was the last consumer (ie, there are no pipe destinations or other 'data' event listeners), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    • ev: Event
    • handler: ((...args: Events<string>[Event]) => any)
        • (...args): any
        • Parameters

          • Rest...args: Events<string>[Event]

          Returns any

    Returns this

  • Mostly identical to EventEmitter.on, with the following behavior differences to prevent data loss and unnecessary hangs:

    • Adding a 'data' event handler will trigger the flow of data

    • Adding a 'readable' event handler when there is data waiting to be read will cause 'readable' to be emitted immediately.

    • Adding an 'endish' event handler ('end', 'finish', etc.) which has already passed will cause the event to be emitted immediately and all handlers removed.

    • Adding an 'error' event handler after an error has been emitted will cause the event to be re-emitted immediately with the error previously raised.

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    • ev: Event
    • handler: ((...args: Events<string>[Event]) => any)
        • (...args): any
        • Parameters

          • Rest...args: Events<string>[Event]

          Returns any

    Returns this

  • Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    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 event listener to the beginning of the listeners array.

    import { EventEmitter } from 'node:events';
    const myEE = new EventEmitter();
    myEE.once('foo', () => console.log('a'));
    myEE.prependOnceListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.3.0

  • Pause the stream

    Returns void

  • Pipe all data emitted by this stream into the destination provided.

    Triggers the flow of data.

    Type Parameters

    • W extends Writable

    Parameters

    • dest: W
    • Optionalopts: PipeOptions

    Returns W

  • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Return a void Promise that resolves once the stream ends.

    Returns Promise<void>

  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    import { EventEmitter } from 'node:events';
    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v9.4.0

  • Low-level explicit read method.

    In objectMode, the argument is ignored, and one item is returned if available.

    n is the number of bytes (or in the case of encoding streams, characters) to consume. If n is not provided, then the entire buffer is returned, or null is returned if no data is available.

    If n is greater that the amount of data in the internal buffer, then null is returned.

    Parameters

    • Optionaln: null | number

    Returns null | string

  • Mostly identical to EventEmitter.removeAllListeners

    If all 'data' event handlers are removed, and they were the last consumer (ie, there are no pipe destinations), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    Returns this

  • Alias for Minipass#off

    Type Parameters

    • Event extends keyof Events<string>

    Parameters

    • ev: Event
    • handler: ((...args: Events<string>[Event]) => any)
        • (...args): any
        • Parameters

          • Rest...args: Events<string>[Event]

          Returns any

    Returns this

  • Resume the stream if it is currently in a paused state

    If called when there are no pipe destinations or data event listeners, this will place the stream in a "discarded" state, where all data will be thrown away. The discarded state is removed if a pipe destination or data handler is added, if pause() is called, or if any synchronous or asynchronous iteration is started.

    Returns void

  • Parameters

    • _enc: Encoding

    Returns void

    • Encoding may only be set at instantiation time
  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • n: number

    Returns this

    v0.3.5

  • Fully unhook a piped destination stream.

    If the destination stream was the only consumer of this stream (ie, there are no other piped destinations or 'data' event listeners) then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    • W extends Writable

    Parameters

    • dest: W

    Returns void

  • Write data into the stream

    If the chunk written is a string, and encoding is not specified, then utf8 will be assumed. If the stream encoding matches the encoding of a written string, and the state of the string decoder allows it, then the string will be passed through to either the output or the internal buffer without any processing. Otherwise, it will be turned into a Buffer object for processing into the desired encoding.

    If provided, cb function is called immediately before return for sync streams, or on next tick for async streams, because for this base class, a chunk is considered "processed" once it is accepted and either emitted or buffered. That is, the callback does not indicate that the chunk has been eventually emitted, though of course child classes can override this function to do whatever processing is required and call super.write(...) only once processing is completed.

    Parameters

    • chunk: ContiguousData
    • Optionalcb: (() => void)
        • (): void
        • Returns void

    Returns boolean

  • Write data into the stream

    If the chunk written is a string, and encoding is not specified, then utf8 will be assumed. If the stream encoding matches the encoding of a written string, and the state of the string decoder allows it, then the string will be passed through to either the output or the internal buffer without any processing. Otherwise, it will be turned into a Buffer object for processing into the desired encoding.

    If provided, cb function is called immediately before return for sync streams, or on next tick for async streams, because for this base class, a chunk is considered "processed" once it is accepted and either emitted or buffered. That is, the callback does not indicate that the chunk has been eventually emitted, though of course child classes can override this function to do whatever processing is required and call super.write(...) only once processing is completed.

    Parameters

    • chunk: ContiguousData
    • Optionalencoding: Encoding
    • Optionalcb: (() => void)
        • (): void
        • Returns void

    Returns boolean

  • Experimental

    Listens once to the abort event on the provided signal.

    Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

    This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

    Returns a disposable so that it may be unsubscribed from more easily.

    import { addAbortListener } from 'node:events';

    function example(signal) {
    let disposable;
    try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
    // Do something when signal is aborted.
    });
    } finally {
    disposable?.[Symbol.dispose]();
    }
    }

    Parameters

    • signal: AbortSignal
    • resource: ((event: Event) => void)
        • (event): void
        • Parameters

          • event: Event

          Returns void

    Returns Disposable

    Disposable that removes the abort listener.

    v20.5.0

  • Returns a copy of the array of listeners for the event named eventName.

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

    For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

    import { getEventListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget
    • name: string | symbol

    Returns Function[]

    v15.2.0, v14.17.0

  • Returns the currently set max amount of listeners.

    For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

    For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

    import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    console.log(getMaxListeners(ee)); // 10
    setMaxListeners(11, ee);
    console.log(getMaxListeners(ee)); // 11
    }
    {
    const et = new EventTarget();
    console.log(getMaxListeners(et)); // 10
    setMaxListeners(11, et);
    console.log(getMaxListeners(et)); // 11
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget

    Returns number

    v19.9.0

  • A class method that returns the number of listeners for the given eventName registered on the given emitter.

    import { EventEmitter, listenerCount } from 'node:events';

    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter<DefaultEventMap>

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

    v0.9.12

    Since v3.2.0 - Use listenerCount instead.

  • import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here

    Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

    An AbortSignal can be used to cancel waiting on events:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Use the close option to specify an array of event names that will end the iteration:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    ee.emit('close');
    });

    for await (const event of on(ee, 'foo', { close: ['close'] })) {
    console.log(event); // prints ['bar'] [42]
    }
    // the loop will exit after 'close' is emitted
    console.log('done'); // prints 'done'

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterableIterator<any[]>

    An AsyncIterator that iterates eventName events emitted by the emitter

    v13.6.0, v12.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterableIterator<any[]>

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

    import { once, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.error('error happened', err);
    }

    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 'error' event itself, then it is treated as any other kind of event without special handling:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.error('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

    v11.13.0, v10.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optionaln: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]

    Returns void

    v15.4.0