The EventEmitter class is defined and exposed by the node:events module:

import { EventEmitter } from 'node:events';

All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when existing listeners are removed.

It supports the following option:

Since

v0.1.26

interface ServerHttp2Session {
    alpnProtocol?: string;
    closed: boolean;
    connecting: boolean;
    destroyed: boolean;
    encrypted?: boolean;
    localSettings: Settings;
    originSet?: string[];
    pendingSettingsAck: boolean;
    remoteSettings: Settings;
    server: Http2SecureServer | Http2Server;
    socket: Socket | TLSSocket;
    state: SessionState;
    type: number;
    [captureRejectionSymbol]?<K>(error, event, ...args): void;
    addListener(event, listener): this;
    addListener(event, listener): this;
    addListener(event, listener): this;
    altsvc(alt, originOrStream): void;
    close(callback?): void;
    destroy(error?, code?): void;
    emit(event, session, socket): boolean;
    emit(event, stream, headers, flags): boolean;
    emit(event, ...args): boolean;
    eventNames(): (string | symbol)[];
    getMaxListeners(): number;
    goaway(code?, lastStreamID?, opaqueData?): void;
    listenerCount<K>(eventName, listener?): number;
    listeners<K>(eventName): Function[];
    off<K>(eventName, listener): this;
    on(event, listener): this;
    on(event, listener): this;
    on(event, listener): this;
    once(event, listener): this;
    once(event, listener): this;
    once(event, listener): this;
    origin(...origins): void;
    ping(callback): boolean;
    ping(payload, callback): boolean;
    prependListener(event, listener): this;
    prependListener(event, listener): this;
    prependListener(event, listener): this;
    prependOnceListener(event, listener): this;
    prependOnceListener(event, listener): this;
    prependOnceListener(event, listener): this;
    rawListeners<K>(eventName): Function[];
    ref(): void;
    removeAllListeners(eventName?): this;
    removeListener<K>(eventName, listener): this;
    setLocalWindowSize(windowSize): void;
    setMaxListeners(n): this;
    setTimeout(msecs, callback?): void;
    settings(settings, callback?): void;
    unref(): void;
}

Hierarchy (view full)

Properties

alpnProtocol?: string

Value will be undefined if the Http2Session is not yet connected to a socket, h2c if the Http2Session is not connected to a TLSSocket, or will return the value of the connected TLSSocket's own alpnProtocol property.

Since

v9.4.0

closed: boolean

Will be true if this Http2Session instance has been closed, otherwise false.

Since

v9.4.0

connecting: boolean

Will be true if this Http2Session instance is still connecting, will be set to false before emitting connect event and/or calling the http2.connect callback.

Since

v10.0.0

destroyed: boolean

Will be true if this Http2Session instance has been destroyed and must no longer be used, otherwise false.

Since

v8.4.0

encrypted?: boolean

Value is undefined if the Http2Session session socket has not yet been connected, true if the Http2Session is connected with a TLSSocket, and false if the Http2Session is connected to any other kind of socket or stream.

Since

v9.4.0

localSettings: Settings

A prototype-less object describing the current local settings of this Http2Session. The local settings are local to thisHttp2Session instance.

Since

v8.4.0

originSet?: string[]

If the Http2Session is connected to a TLSSocket, the originSet property will return an Array of origins for which the Http2Session may be considered authoritative.

The originSet property is only available when using a secure TLS connection.

Since

v9.4.0

pendingSettingsAck: boolean

Indicates whether the Http2Session is currently waiting for acknowledgment of a sent SETTINGS frame. Will be true after calling the http2session.settings() method. Will be false once all sent SETTINGS frames have been acknowledged.

Since

v8.4.0

remoteSettings: Settings

A prototype-less object describing the current remote settings of thisHttp2Session. The remote settings are set by the connected HTTP/2 peer.

Since

v8.4.0

socket: Socket | TLSSocket

Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but limits available methods to ones safe to use with HTTP/2.

destroy, emit, end, pause, read, resume, and write will throw an error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for more information.

setTimeout method will be called on this Http2Session.

All other interactions will be routed directly to the socket.

Since

v8.4.0

Provides miscellaneous information about the current state of theHttp2Session.

An object describing the current status of this Http2Session.

Since

v8.4.0

type: number

The http2session.type will be equal to http2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a server, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a client.

Since

v8.4.0

Methods

  • Type Parameters

    • K

    Parameters

    Returns void

  • Alias for emitter.on(eventName, listener).

    Parameters

    Returns this

    Since

    v0.1.26

  • Parameters

    Returns this

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

  • Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

    const http2 = require('node:http2');

    const server = http2.createServer();
    server.on('session', (session) => {
    // Set altsvc for origin https://example.org:80
    session.altsvc('h2=":8000"', 'https://example.org:80');
    });

    server.on('stream', (stream) => {
    // Set altsvc for a specific stream
    stream.session.altsvc('h2=":8000"', stream.id);
    });

    Sending an ALTSVC frame with a specific stream ID indicates that the alternate service is associated with the origin of the given Http2Stream.

    The alt and origin string must contain only ASCII bytes and are strictly interpreted as a sequence of ASCII bytes. The special value 'clear'may be passed to clear any previously set alternative service for a given domain.

    When a string is passed for the originOrStream argument, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL 'https://example.org/foo/bar' is the ASCII string'https://example.org'. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.

    A URL object, or any object with an origin property, may be passed asoriginOrStream, in which case the value of the origin property will be used. The value of the origin property must be a properly serialized ASCII origin.

    Parameters

    • alt: string

      A description of the alternative service configuration as defined by RFC 7838.

    • originOrStream: string | number | URL | AlternativeServiceOptions

      Either a URL string specifying the origin (or an Object with an origin property) or the numeric identifier of an active Http2Stream as given by the http2stream.id property.

    Returns void

    Since

    v9.4.0

  • Gracefully closes the Http2Session, allowing any existing streams to complete on their own and preventing new Http2Stream instances from being created. Once closed, http2session.destroy()might be called if there are no open Http2Stream instances.

    If specified, the callback function is registered as a handler for the'close' event.

    Parameters

    • Optional callback: (() => void)
        • (): void
        • Returns void

    Returns void

    Since

    v9.4.0

  • Immediately terminates the Http2Session and the associated net.Socket or tls.TLSSocket.

    Once destroyed, the Http2Session will emit the 'close' event. If error is not undefined, an 'error' event will be emitted immediately before the 'close' event.

    If there are any remaining open Http2Streams associated with the Http2Session, those will also be destroyed.

    Parameters

    • Optional error: Error

      An Error object if the Http2Session is being destroyed due to an error.

    • Optional code: number

      The HTTP/2 error code to send in the final GOAWAY frame. If unspecified, and error is not undefined, the default is INTERNAL_ERROR, otherwise defaults to NO_ERROR.

    Returns void

    Since

    v8.4.0

  • Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import { EventEmitter } from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Parameters

    Returns boolean

    Since

    v0.1.26

  • Parameters

    Returns boolean

  • Parameters

    • event: string | symbol
    • Rest ...args: any[]

    Returns boolean

  • 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)[]

    Since

    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

    Since

    v1.0.0

  • Transmits a GOAWAY frame to the connected peer without shutting down theHttp2Session.

    Parameters

    • Optional code: number

      An HTTP/2 error code

    • Optional lastStreamID: number

      The numeric ID of the last processed Http2Stream

    • Optional opaqueData: ArrayBufferView

      A TypedArray or DataView instance containing additional data to be carried within the GOAWAY frame.

    Returns void

    Since

    v9.4.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

    • Optional listener: Function

      The event handler function

    Returns number

    Since

    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[]

    Since

    v0.1.26

  • Alias for emitter.removeListener().

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

    Since

    v10.0.0

  • Adds the listener function to the end 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.on('connection', (stream) => {
    console.log('someone connected!');
    });

    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.prependListener() 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.on('foo', () => console.log('a'));
    myEE.prependListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Parameters

    • event: "connect"

      The name of the event.

    • listener: ((session, socket) => void)

      The callback function

    Returns this

    Since

    v0.1.101

  • Parameters

    Returns this

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    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

    Parameters

    • event: "connect"

      The name of the event.

    • listener: ((session, socket) => void)

      The callback function

    Returns this

    Since

    v0.3.0

  • Parameters

    Returns this

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

  • Submits an ORIGIN frame (as defined by RFC 8336) to the connected client to advertise the set of origins for which the server is capable of providing authoritative responses.

    const http2 = require('node:http2');
    const options = getSecureOptionsSomehow();
    const server = http2.createSecureServer(options);
    server.on('stream', (stream) => {
    stream.respond();
    stream.end('ok');
    });
    server.on('session', (session) => {
    session.origin('https://example.com', 'https://example.org');
    });

    When a string is passed as an origin, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL 'https://example.org/foo/bar' is the ASCII string 'https://example.org'. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.

    A URL object, or any object with an origin property, may be passed as an origin, in which case the value of the origin property will be used. The value of the origin property must be a properly serialized ASCII origin.

    Alternatively, the origins option may be used when creating a new HTTP/2 server using the http2.createSecureServer() method:

    const http2 = require('node:http2');
    const options = getSecureOptionsSomehow();
    options.origins = ['https://example.com', 'https://example.org'];
    const server = http2.createSecureServer(options);
    server.on('stream', (stream) => {
    stream.respond();
    stream.end('ok');
    });

    Parameters

    • Rest ...origins: (string | URL | {
          origin: string;
      })[]

      One or more URL Strings passed as separate arguments.

    Returns void

    Since

    v10.12.0

  • Sends a PING frame to the connected HTTP/2 peer. A callback function must be provided. The method will return true if the PING was sent, false otherwise.

    The maximum number of outstanding (unacknowledged) pings is determined by the maxOutstandingPings configuration option. The default maximum is 10.

    If provided, the payload must be a Buffer, TypedArray, or DataView containing 8 bytes of data that will be transmitted with the PING and returned with the ping acknowledgment.

    The callback will be invoked with three arguments: an error argument that will be null if the PING was successfully acknowledged, a duration argument that reports the number of milliseconds elapsed since the ping was sent and the acknowledgment was received, and a Buffer containing the 8-byte PING payload.

    session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
    if (!err) {
    console.log(`Ping acknowledged in ${duration} milliseconds`);
    console.log(`With payload '${payload.toString()}'`);
    }
    });

    If the payload argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the PING duration.

    Parameters

    • callback: ((err, duration, payload) => void)
        • (err, duration, payload): void
        • Parameters

          Returns void

    Returns boolean

    Since

    v8.9.3

  • Parameters

    • payload: ArrayBufferView
    • callback: ((err, duration, payload) => void)
        • (err, duration, payload): void
        • Parameters

          Returns void

    Returns boolean

  • 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.

    Parameters

    • event: "connect"

      The name of the event.

    • listener: ((session, socket) => void)

      The callback function

    Returns this

    Since

    v6.0.0

  • Parameters

    Returns this

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

  • 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.

    Parameters

    • event: "connect"

      The name of the event.

    • listener: ((session, socket) => void)

      The callback function

    Returns this

    Since

    v6.0.0

  • Parameters

    Returns this

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

  • 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[]

    Since

    v9.4.0

  • Calls ref() on this Http2Session instance's underlying net.Socket.

    Returns void

    Since

    v9.4.0

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

    Parameters

    • Optional eventName: string | symbol

    Returns this

    Since

    v0.1.26

  • Removes the specified listener from the listener array for the event named eventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

    Once an event is emitted, all listeners attached to it at the 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 not remove them fromemit() in progress. Subsequent events behave as expected.

    import { EventEmitter } from 'node:events';
    class MyEmitter extends EventEmitter {}
    const myEmitter = new MyEmitter();

    const callbackA = () => {
    console.log('A');
    myEmitter.removeListener('event', callbackB);
    };

    const callbackB = () => {
    console.log('B');
    };

    myEmitter.on('event', callbackA);

    myEmitter.on('event', callbackB);

    // callbackA removes listener callbackB but it will still be called.
    // Internal listener array at time of emit [callbackA, callbackB]
    myEmitter.emit('event');
    // Prints:
    // A
    // B

    // callbackB is now removed.
    // Internal listener array [callbackA]
    myEmitter.emit('event');
    // Prints:
    // A

    Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

    When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

    import { EventEmitter } from 'node:events';
    const ee = new EventEmitter();

    function pong() {
    console.log('pong');
    }

    ee.on('ping', pong);
    ee.once('ping', pong);
    ee.removeListener('ping', pong);

    ee.emit('ping');
    ee.emit('ping');

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

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

    Since

    v0.1.26

  • Sets the local endpoint's window size. The windowSize is the total window size to set, not the delta.

    const http2 = require('node:http2');

    const server = http2.createServer();
    const expectedWindowSize = 2 ** 20;
    server.on('connect', (session) => {

    // Set local window size to be 2 ** 20
    session.setLocalWindowSize(expectedWindowSize);
    });

    Parameters

    • windowSize: number

    Returns void

    Since

    v15.3.0, v14.18.0

  • 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

    Since

    v0.3.5

  • Used to set a callback function that is called when there is no activity on the Http2Session after msecs milliseconds. The given callback is registered as a listener on the 'timeout' event.

    Parameters

    • msecs: number
    • Optional callback: (() => void)
        • (): void
        • Returns void

    Returns void

    Since

    v8.4.0

  • Updates the current local settings for this Http2Session and sends a new SETTINGS frame to the connected HTTP/2 peer.

    Once called, the http2session.pendingSettingsAck property will be true while the session is waiting for the remote peer to acknowledge the new settings.

    The new settings will not become effective until the SETTINGS acknowledgment is received and the 'localSettings' event is emitted. It is possible to send multiple SETTINGS frames while acknowledgment is still pending.

    Parameters

    • settings: Settings
    • Optional callback: ((err, settings, duration) => void)

      Callback that is called once the session is connected or right away if the session is already connected.

        • (err, settings, duration): void
        • Parameters

          Returns void

    Returns void

    Since

    v8.4.0

  • Calls unref() on this Http2Sessioninstance's underlying net.Socket.

    Returns void

    Since

    v9.4.0