Milliseconds to subtract from the server-provided keep-alive: timeout=... hint when determining socket expiration time. This buffer helps ensure the agent closes the socket slightly before the server does, reducing the chance of sending a request on a socket that’s about to be closed by the server.
constructor
https.Agent.constructor
Not implemented in Bun
Referenced types
interface AgentOptions
- agentKeepAliveTimeoutBuffer?: number
- allowPartialTrustChain?: boolean
Treat intermediate (non-self-signed) certificates in the trust CA certificate list as trusted.
- ALPNCallback?: (arg: { protocols: string[]; servername: string }) => undefined | string
If set, this will be called when a client opens a connection using the ALPN extension. One argument will be passed to the callback: an object containing
servernameandprotocolsfields, respectively containing the server name from the SNI extension (if any) and an array of ALPN protocol name strings. The callback must return either one of the strings listed inprotocols, which will be returned to the client as the selected ALPN protocol, orundefined, to reject the connection with a fatal alert. If a string is returned that does not match one of the client's ALPN protocols, an error will be thrown. This option cannot be used with theALPNProtocolsoption, and setting both options will throw an error. - ALPNProtocols?: readonly string[] | ArrayBufferView<ArrayBufferLike>
An array of strings or a Buffer naming possible ALPN protocols. (Protocols should be ordered by their priority.)
- cert?: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike>[]
Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.
- ciphers?: string
Cipher suite specification, replacing the default. For more information, see modifying the default cipher suite. Permitted ciphers can be obtained via tls.getCiphers(). Cipher names must be uppercased in order for OpenSSL to accept them.
- ecdhCurve?: string
A string describing a named curve or a colon separated list of curve NIDs or names, for example P-521:P-384:P-256, to use for ECDH key agreement. Set to auto to select the curve automatically. Use crypto.getCurves() to obtain a list of available curve names. On recent releases, openssl ecparam -list_curves will also display the name and description of each available elliptic curve. Default: tls.DEFAULT_ECDH_CURVE.
- enableTrace?: boolean
When enabled, TLS packet trace information is written to
stderr. This can be used to debug TLS connection problems. - honorCipherOrder?: boolean
Attempt to use the server's cipher suite preferences instead of the client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions
- keepAlive?: boolean
Keep sockets around in a pool to be used by other requests in the future. Default = false
- keepAliveMsecs?: number
When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. Only relevant if keepAlive is set to true.
- key?: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike> | KeyObject[]
Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
- maxFreeSockets?: number
Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
- maxSockets?: number
Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
- maxTotalSockets?: number
Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
- maxVersion?: SecureVersion
Optionally set the maximum TLS version to allow. One of
'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Cannot be specified along with thesecureProtocoloption, use one or the other. Default:'TLSv1.3', unless changed using CLI options. Using--tls-max-v1.2sets the default to'TLSv1.2'. Using--tls-max-v1.3sets the default to'TLSv1.3'. If multiple of the options are provided, the highest maximum is used. - minVersion?: SecureVersion
Optionally set the minimum TLS version to allow. One of
'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Cannot be specified along with thesecureProtocoloption, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability. Default:'TLSv1.2', unless changed using CLI options. Using--tls-v1.0sets the default to'TLSv1'. Using--tls-v1.1sets the default to'TLSv1.1'. Using--tls-min-v1.3sets the default to 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. - pfx?: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike> | PxfObject[]
PFX or PKCS12 encoded private key and certificate chain. pfx is an alternative to providing key and cert individually. PFX is usually encrypted, if it is, passphrase will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form {buf: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
- proxyEnv?: ProxyEnv
Environment variables for proxy configuration. See Built-in Proxy Support for details.
- pskCallback?: (hint: null | string) => null | PSKCallbackNegotation
When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity
hintprovided by the server ornullin case of TLS 1.3 wherehintwas removed. It will be necessary to provide a customtls.checkServerIdentity()for the connection as the default one will try to check hostname/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the RFC 4279. - requestCert?: boolean
If true the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to false.
- secureOptions?: number
Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options
- secureProtocol?: string
Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use minVersion and maxVersion instead. The possible values are listed as SSL_METHODS, use the function names as strings. For example, use 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. Default: none, see minVersion.
- sessionIdContext?: string
Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.
- sessionTimeout?: number
The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default: 300.
- sigalgs?: string
Colon-separated list of supported signature algorithms. The list can contain digest algorithms (SHA256, MD5 etc.), public key algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).
- SNICallback?: (servername: string, cb: (err: null | Error, ctx?: SecureContext) => void) => void
SNICallback(servername, cb) <Function> A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: servername and cb. SNICallback should invoke cb(null, ctx), where ctx is a SecureContext instance. (tls.createSecureContext(...) can be used to get a proper SecureContext.) If SNICallback wasn't provided the default callback with high-level API will be used (see below).
- ticketKeys?: Buffer<ArrayBufferLike>
48-bytes of cryptographically strong pseudo-random data. See Session Resumption for more information.
- timeout?: number
Socket timeout in milliseconds. This will set the timeout after the socket is connected.
class Agent
An Agent object for HTTPS similar to http.Agent. See request for more information.
- readonly freeSockets: ReadOnlyDict<Socket[]>
An object which contains arrays of sockets currently awaiting use by the agent when
keepAliveis enabled. Do not modify.Sockets in the
freeSocketslist will be automatically destroyed and removed from the array on'timeout'. - maxFreeSockets: number
By default set to 256. For agents with
keepAliveenabled, this sets the maximum number of sockets that will be left open in the free state. - maxSockets: number
By default set to
Infinity. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value ofagent.getName(). - maxTotalSockets: number
By default set to
Infinity. Determines how many concurrent sockets the agent can have open. UnlikemaxSockets, this parameter applies across all origins. - readonly requests: ReadOnlyDict<IncomingMessage[]>
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
- 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. } } - eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.on(eventName, listener). Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as
net.createConnection(). However, custom agents may override this method in case greater flexibility is desired.A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function, or by passing the socket/stream to
callback.This method is guaranteed to return an instance of the
net.Socketclass, a subclass ofstream.Duplex, unless the user specifies a socket type other thannet.Socket.callbackhas a signature of(err, stream).@param optionsOptions containing connection details. Check
createConnectionfor the format of the options@param callbackCallback function that receives the created socket
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an agent with
keepAliveenabled, then it is best to explicitly shut down the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them.- 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.- ): string;
Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returns
host:port:localAddressorhost:port:localAddress:family. For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.@param optionsA set of options providing information for name generation
- ): void;
Called when
socketis detached from a request and could be persisted by theAgent. Default behavior is to:socket.setKeepAlive(true, this.keepAliveMsecs); socket.unref(); return true;This method can be overridden by a particular
Agentsubclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.The
socketargument can be an instance ofnet.Socket, a subclass ofstream.Duplex. - 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
- 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] ] - eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener(). - 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
- 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
- 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
- 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
- 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'); - 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. - 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. - ): void;
Called when
socketis attached torequestafter being persisted because of the keep-alive options. Default behavior is to:socket.ref();This method can be overridden by a particular
Agentsubclass.The
socketargument can be an instance ofnet.Socket, a subclass ofstream.Duplex. - 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.