Create an HTTP/2 server session from an existing socket.
function
http2.performServerHandshake
A Duplex Stream
Any {@link createServer} options can be provided.
Referenced types
interface ServerOptions<Http1Request extends typeof IncomingMessage = typeof IncomingMessage, Http1Response extends typeof ServerResponse = typeof ServerResponse, Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, Http2Response extends typeof Http2ServerResponse = typeof Http2ServerResponse>
- maxHeaderListPairs?: number
Sets the maximum number of header entries. This is similar to
server.maxHeadersCountorrequest.maxHeadersCountin thenode:httpmodule. The minimum value is1. - maxSendHeaderBlockLength?: number
Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a
'frameError'event being emitted and the stream being closed and destroyed. - maxSessionMemory?: number
Sets the maximum memory that the
Http2Sessionis permitted to use. The value is expressed in terms of number of megabytes, e.g.1equal 1 megabyte. The minimum value allowed is1. This is a credit based limit, existingHttp2Streams may cause this limit to be exceeded, but newHttp2Streaminstances will be rejected while this limit is exceeded. The current number ofHttp2Streamsessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledgedPINGandSETTINGSframes are all counted towards the current limit. - maxSettings?: number
Sets the maximum number of settings entries per
SETTINGSframe. The minimum value allowed is1. - paddingStrategy?: number
Strategy used for determining the amount of padding to use for
HEADERSandDATAframes. - peerMaxConcurrentStreams?: number
Sets the maximum number of concurrent streams for the remote peer as if a
SETTINGSframe had been received. Will be overridden if the remote peer sets its own value formaxConcurrentStreams. - remoteCustomSettings?: number[]
The array of integer values determines the settings types, which are included in the
CustomSettings-property of the received remoteSettings. Please see theCustomSettings-property of theHttp2Settingsobject for more information, on the allowed setting types. - strictFieldWhitespaceValidation?: boolean
If
true, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. - unknownProtocolTimeout?: number
Specifies a timeout in milliseconds that a server should wait when an [
'unknownProtocol'][] is emitted. If the socket has not been destroyed by that time the server will destroy it.
interface ServerHttp2Session<Http1Request extends typeof IncomingMessage = typeof IncomingMessage, Http1Response extends typeof ServerResponse = typeof ServerResponse, Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, Http2Response extends typeof Http2ServerResponse = typeof Http2ServerResponse>
This is the interface from which event-emitting Node.js APIs inherit in the types package. It is not intended for consumer use.
It provides event-mapped definitions similar to EventEmitter, except that its signatures are deliberately permissive: they provide type hinting, but not rigid type-checking, for compatibility reasons.
Classes that inherit directly from EventEmitter in JavaScript can inherit directly from this interface in the type definitions. Classes that are more than one inheritance level away from EventEmitter (eg. net.Socket > stream.Duplex > EventEmitter) must instead copy these method definitions into the derived class. Search "#region InternalEventEmitter" for examples.
- readonly alpnProtocol?: string
Value will be
undefinedif theHttp2Sessionis not yet connected to a socket,h2cif theHttp2Sessionis not connected to aTLSSocket, or will return the value of the connectedTLSSocket's ownalpnProtocolproperty. - readonly closed: boolean
Will be
trueif thisHttp2Sessioninstance has been closed, otherwisefalse. - readonly connecting: boolean
Will be
trueif thisHttp2Sessioninstance is still connecting, will be set tofalsebefore emittingconnectevent and/or calling thehttp2.connectcallback. - readonly destroyed: boolean
Will be
trueif thisHttp2Sessioninstance has been destroyed and must no longer be used, otherwisefalse. - readonly encrypted?: boolean
Value is
undefinedif theHttp2Sessionsession socket has not yet been connected,trueif theHttp2Sessionis connected with aTLSSocket, andfalseif theHttp2Sessionis connected to any other kind of socket or stream. - readonly localSettings: Settings
A prototype-less object describing the current local settings of this
Http2Session. The local settings are local to thisHttp2Sessioninstance. - readonly originSet?: string[]
If the
Http2Sessionis connected to aTLSSocket, theoriginSetproperty will return anArrayof origins for which theHttp2Sessionmay be considered authoritative.The
originSetproperty is only available when using a secure TLS connection. - readonly pendingSettingsAck: boolean
Indicates whether the
Http2Sessionis currently waiting for acknowledgment of a sentSETTINGSframe. Will betrueafter calling thehttp2session.settings()method. Will befalseonce all sentSETTINGSframes have been acknowledged. - readonly remoteSettings: Settings
A prototype-less object describing the current remote settings of this
Http2Session. The remote settings are set by the connected HTTP/2 peer. - readonly server: Http2Server<Http1Request, Http1Response, Http2Request, Http2Response> | Http2SecureServer<Http1Request, Http1Response, Http2Request, Http2Response>
- readonly socket: Socket | TLSSocket
Returns a
Proxyobject that acts as anet.Socket(ortls.TLSSocket) but limits available methods to ones safe to use with HTTP/2.destroy,emit,end,pause,read,resume, andwritewill throw an error with codeERR_HTTP2_NO_SOCKET_MANIPULATION. SeeHttp2Session and Socketsfor more information.setTimeoutmethod will be called on thisHttp2Session.All other interactions will be routed directly to the socket.
- readonly state: SessionState
Provides miscellaneous information about the current state of the
Http2Session.An object describing the current status of this
Http2Session. - readonly type: number
The
http2session.typewill be equal tohttp2.constants.NGHTTP2_SESSION_SERVERif thisHttp2Sessioninstance is a server, andhttp2.constants.NGHTTP2_SESSION_CLIENTif the instance is a client. - event: string | symbol,...args: any[]): void;
The
Symbol.for('nodejs.rejection')method is called in case a promise rejection happens when emitting an event andcaptureRejectionsis enabled on the emitter. It is possible to useevents.captureRejectionSymbolin place ofSymbol.for('nodejs.rejection').import { EventEmitter, captureRejectionSymbol } from 'node:events'; class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } } - addListener<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Alias for
emitter.on(eventName, listener).eventName: string | symbol,listener: (...args: any[]) => void): this;Alias for
emitter.on(eventName, listener). - alt: string,): void;
Submits an
ALTSVCframe (as defined by RFC 7838) to the connected client.import http2 from '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
ALTSVCframe with a specific stream ID indicates that the alternate service is associated with the origin of the givenHttp2Stream.The
altand 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
originOrStreamargument, 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
URLobject, or any object with anoriginproperty, may be passed asoriginOrStream, in which case the value of theoriginproperty will be used. The value of theoriginproperty must be a properly serialized ASCII origin.@param altA description of the alternative service configuration as defined by
RFC 7838.@param originOrStreamEither a URL string specifying the origin (or an
Objectwith anoriginproperty) or the numeric identifier of an activeHttp2Streamas given by thehttp2stream.idproperty. - callback?: () => void): void;
Gracefully closes the
Http2Session, allowing any existing streams to complete on their own and preventing newHttp2Streaminstances from being created. Once closed,http2session.destroy()might be called if there are no openHttp2Streaminstances.If specified, the
callbackfunction is registered as a handler for the'close'event. - code?: number): void;
Immediately terminates the
Http2Sessionand the associatednet.Socketortls.TLSSocket.Once destroyed, the
Http2Sessionwill emit the'close'event. Iferroris not undefined, an'error'event will be emitted immediately before the'close'event.If there are any remaining open
Http2Streamsassociated with theHttp2Session, those will also be destroyed.@param errorAn
Errorobject if theHttp2Sessionis being destroyed due to an error.@param codeThe HTTP/2 error code to send in the final
GOAWAYframe. If unspecified, anderroris not undefined, the default isINTERNAL_ERROR, otherwise defaults toNO_ERROR. - emit<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,): boolean;
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
trueif the event had listeners,falseotherwise.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 listeneremit(eventName: string | symbol,...args: any[]): boolean;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
trueif the event had listeners,falseotherwise.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 Returns an array listing the events for which the emitter has registered listeners.
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 the current max listener value for the
EventEmitterwhich is either set byemitter.setMaxListeners(n)or defaults toevents.defaultMaxListeners.- code?: number,lastStreamID?: number,opaqueData?: ArrayBufferView<ArrayBufferLike>): void;
Transmits a
GOAWAYframe to the connected peer without shutting down theHttp2Session.@param codeAn HTTP/2 error code
@param lastStreamIDThe numeric ID of the last processed
Http2Stream@param opaqueDataA
TypedArrayorDataViewinstance containing additional data to be carried within theGOAWAYframe. - listenerCount<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener?: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): number;
Returns the number of listeners listening for the event named
eventName. Iflisteneris provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
eventName: string | symbol,listener?: (...args: any[]) => void): number;Returns the number of listeners listening for the event named
eventName. Iflisteneris provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- listeners<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E): (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void[];
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] ]eventName: string | symbol): (...args: any[]) => void[];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] ] - off<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Alias for
emitter.removeListener().off(eventName: string | symbol,listener: (...args: any[]) => void): this;Alias for
emitter.removeListener(). - on<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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@param eventNameThe name of the event.
@param listenerThe callback function
on(eventName: string | symbol,listener: (...args: any[]) => void): this;Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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@param eventNameThe name of the event.
@param listenerThe callback function
- once<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis 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@param eventNameThe name of the event.
@param listenerThe callback function
once(eventName: string | symbol,listener: (...args: any[]) => void): this;Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis 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@param eventNameThe name of the event.
@param listenerThe callback function
- ): void;
Submits an
ORIGINframe (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.import http2 from '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
URLobject, or any object with anoriginproperty, may be passed as anorigin, in which case the value of theoriginproperty will be used. The value of theoriginproperty must be a properly serialized ASCII origin.Alternatively, the
originsoption may be used when creating a new HTTP/2 server using thehttp2.createSecureServer()method:import http2 from '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'); });@param originsOne or more URL Strings passed as separate arguments.
- ping(): boolean;
Sends a
PINGframe to the connected HTTP/2 peer. Acallbackfunction must be provided. The method will returntrueif thePINGwas sent,falseotherwise.The maximum number of outstanding (unacknowledged) pings is determined by the
maxOutstandingPingsconfiguration option. The default maximum is 10.If provided, the
payloadmust be aBuffer,TypedArray, orDataViewcontaining 8 bytes of data that will be transmitted with thePINGand returned with the ping acknowledgment.The callback will be invoked with three arguments: an error argument that will be
nullif thePINGwas successfully acknowledged, adurationargument that reports the number of milliseconds elapsed since the ping was sent and the acknowledgment was received, and aBuffercontaining the 8-bytePINGpayload.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
payloadargument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of thePINGduration. - prependListener<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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.@param eventNameThe name of the event.
@param listenerThe callback function
eventName: string | symbol,listener: (...args: any[]) => void): this;Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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.@param eventNameThe name of the event.
@param listenerThe callback function
- prependOnceListener<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Adds a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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.@param eventNameThe name of the event.
@param listenerThe callback function
eventName: string | symbol,listener: (...args: any[]) => void): this;Adds a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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.@param eventNameThe name of the event.
@param listenerThe callback function
- rawListeners<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E): (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => 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');eventName: string | symbol): (...args: any[]) => 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'); Calls
ref()on thisHttp2Sessioninstance's underlyingnet.Socket.- removeAllListeners<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName?: E): this;
Removes all listeners, or those of the specified
eventName.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitterinstance 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.eventName?: string | symbol): this;Removes all listeners, or those of the specified
eventName.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitterinstance 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. - removeListener<E extends keyof ServerHttp2SessionEventMap<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse>>(eventName: E,listener: (...args: ServerHttp2SessionEventMap<Http1Request, Http1Response, Http2Request, Http2Response>[E]) => void): this;
Removes the specified
listenerfrom the listener array for the event namedeventName.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 specifiedeventName, thenremoveListener()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()orremoveAllListeners()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: // ABecause listeners are managed using an internal array, calling this will change the position indexes 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 theonce('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.eventName: string | symbol,listener: (...args: any[]) => void): this;Removes the specified
listenerfrom the listener array for the event namedeventName.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 specifiedeventName, thenremoveListener()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()orremoveAllListeners()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: // ABecause listeners are managed using an internal array, calling this will change the position indexes 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 theonce('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. - windowSize: number): void;
Sets the local endpoint's window size. The
windowSizeis the total window size to set, not the delta.import http2 from '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); }); - n: number): this;
By default
EventEmitters will print a warning if more than10listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()method allows the limit to be modified for this specificEventEmitterinstance. The value can be set toInfinity(or0) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter, so that calls can be chained. - msecs: number,callback?: () => void): void;
Used to set a callback function that is called when there is no activity on the
Http2Sessionaftermsecsmilliseconds. The givencallbackis registered as a listener on the'timeout'event. - ): void;
Updates the current local settings for this
Http2Sessionand sends a newSETTINGSframe to the connected HTTP/2 peer.Once called, the
http2session.pendingSettingsAckproperty will betruewhile the session is waiting for the remote peer to acknowledge the new settings.The new settings will not become effective until the
SETTINGSacknowledgment is received and the'localSettings'event is emitted. It is possible to send multipleSETTINGSframes while acknowledgment is still pending.@param callbackCallback that is called once the session is connected or right away if the session is already connected.
Calls
unref()on thisHttp2Sessioninstance's underlyingnet.Socket.