Coconstructor
Bun

constructor

https.Agent.constructor

Not implemented in Bun

constructor Agent(
options?: AgentOptions
): Agent;

Referenced types

interface AgentOptions

  • agentKeepAliveTimeoutBuffer?: number

    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.

  • 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 servername and protocols fields, 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 in protocols, which will be returned to the client as the selected ALPN protocol, or undefined, 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 the ALPNProtocols option, 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.)

  • ca?: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike>[]

    Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option.

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

  • checkServerIdentity?: (hostname: string, cert: PeerCertificate) => undefined | Error
  • 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.

  • crl?: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike>[]

    PEM formatted CRLs (Certificate Revocation Lists).

  • defaultPort?: number

    Default port to use when the port is not specified in requests.

  • dhparam?: string | Buffer<ArrayBufferLike>

    'auto' or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. ECDHE-based perfect forward secrecy will still be available.

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

  • family?: number
  • hints?: number
  • 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

  • host?: string
  • 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.

  • localAddress?: string
  • localPort?: number
  • 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 the secureProtocol option, use one or the other. Default: 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the highest maximum is used.

  • minDHSize?: number
  • 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 the secureProtocol option, 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.0 sets the default to 'TLSv1'. Using --tls-v1.1 sets the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.

  • noDelay?: boolean
  • passphrase?: string

    Shared passphrase used for a single private key and/or a PFX.

  • path?: string
  • 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.

  • port?: number
  • protocol?: string

    The protocol to use for the agent.

  • proxyEnv?: ProxyEnv
  • pskCallback?: (hint: null | string) => null | PSKCallbackNegotation

    When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity hint provided by the server or null in case of TLS 1.3 where hint was removed. It will be necessary to provide a custom tls.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.

  • rejectUnauthorized?: boolean

    If true the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true.

  • requestCert?: boolean

    If true the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to false.

  • scheduling?: 'fifo' | 'lifo'

    Scheduling strategy to apply when picking the next free socket to use.

  • secureContext?: SecureContext

    An optional TLS context object from tls.createSecureContext()

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

  • servername?: string
  • session?: Buffer<ArrayBufferLike>
  • 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 keepAlive is enabled. Do not modify.

    Sockets in the freeSockets list will be automatically destroyed and removed from the array on 'timeout'.

  • maxFreeSockets: number

    By default set to 256. For agents with keepAlive enabled, 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 of agent.getName().

  • maxTotalSockets: number

    By default set to Infinity. Determines how many concurrent sockets the agent can have open. Unlike maxSockets, 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.

  • readonly sockets: ReadOnlyDict<Socket[]>

    An object which contains arrays of sockets currently in use by the agent. Do not modify.

  • error: Error,
    event: string | symbol,
    ...args: any[]
    ): void;

    The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.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 string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    Alias for emitter.on(eventName, listener).

  • options: RequestOptions,
    callback?: (err: null | Error, stream: Duplex) => void
    ): undefined | null | Duplex;

    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.Socket class, a subclass of stream.Duplex, unless the user specifies a socket type other than net.Socket.

    callback has a signature of (err, stream).

    @param options

    Options containing connection details. Check createConnection for the format of the options

    @param callback

    Callback function that receives the created socket

  • destroy(): void;

    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 keepAlive enabled, 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.

  • emit<E extends string | symbol>(
    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 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
    
  • eventNames(): string | symbol[];

    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) ]
    
  • getMaxListeners(): number;

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

  • options?: RequestOptions
    ): string;

    Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returnshost:port:localAddress or host: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 options

    A set of options providing information for name generation

  • socket: Duplex
    ): void;

    Called when socket is 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 Agent subclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.

    The socket argument can be an instance of net.Socket, a subclass of stream.Duplex.

  • listenerCount<E extends string | symbol>(
    eventName: string | symbol,
    listener?: (...args: any[]) => void
    ): number;

    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.

    @param eventName

    The name of the event being listened for

    @param listener

    The event handler function

  • listeners<E extends string | symbol>(
    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 string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    Alias for emitter.removeListener().

  • on<E extends string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    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
    
    @param eventName

    The name of the event.

    @param listener

    The callback function

  • once<E extends string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): 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
    
    @param eventName

    The name of the event.

    @param listener

    The callback function

  • prependListener<E extends string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    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.

    @param eventName

    The name of the event.

    @param listener

    The callback function

  • prependOnceListener<E extends string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this 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 eventName

    The name of the event.

    @param listener

    The callback function

  • rawListeners<E extends string | symbol>(
    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');
    
  • removeAllListeners<E extends string | symbol>(
    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 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.

  • removeListener<E extends string | symbol>(
    eventName: string | symbol,
    listener: (...args: any[]) => void
    ): this;

    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 from emit() 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 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 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.

  • socket: Duplex,
    request: ClientRequest
    ): void;

    Called when socket is attached to request after being persisted because of the keep-alive options. Default behavior is to:

    socket.ref();
    

    This method can be overridden by a particular Agent subclass.

    The socket argument can be an instance of net.Socket, a subclass of stream.Duplex.

  • n: number
    ): this;

    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.