new Agent([options])


  • options <Object> 要在代理上设置的可配置选项集。可以包含以下字段:

    • keepAlive <boolean> 即使没有未完成的请求,也要保持套接字,这样它们就可以被用于将来的请求而无需重新建立 TCP 连接。默认值: false
    • keepAliveMsecs <number> 当使用 keepAlive 选项时,指定用于 TCP Keep-Alive 数据包的初始延迟。当 keepAlive 选项为 falseundefined 时则忽略。默认值: 1000
    • maxSockets <number> 每个主机允许的套接字的最大数量。默认值: Infinity
    • maxFreeSockets <number> 在空闲状态下保持打开的套接字的最大数量。仅当 keepAlive 被设置为 true 时才相关。默认值: 256
    • timeout <number> 套接字的超时时间,以毫秒为单位。这会在套接字被连接之后设置超时时间。

socket.connect() 中的 options 也受支持。

http.request() 使用的默认的 http.globalAgent 具有所有这些值且被设置为各自的默认值。

要配置其中任何一个,则必须创建自定义的 http.Agent 实例。

const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
  • options <Object> Set of configurable options to set on the agent. Can have the following fields:

    • keepAlive <boolean> Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the keep-alive value of the Connection header. The Connection: keep-alive header is always sent when using an agent except when the Connection header is explicitly specified or when the keepAlive and maxSockets options are respectively set to false and Infinity, in which case Connection: close will be used. Default: false.
    • keepAliveMsecs <number> When using the keepAlive option, specifies the initial delay for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Default: 1000.
    • maxSockets <number> Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached. Default: Infinity.
    • maxFreeSockets <number> Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default: 256.
    • timeout <number> Socket timeout in milliseconds. This will set the timeout when the socket is created.

options in socket.connect() are also supported.

The default http.globalAgent that is used by http.request() has all of these values set to their respective defaults.

To configure any of them, a custom http.Agent instance must be created.

const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);