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> 套接字超时(以毫秒为单位)。这将在连接套接字后设置超时。

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. 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. 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 after the socket is connected.

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);