agent-base
将函数转换成 http.Agent 实例
这个模块是一个薄包装围绕基础 http.Agent 类。
它提供了一个抽象类,该类必须定义 connect() 函数,
谁负责创建HTTP的底层套接字
客户端请求将使用。
这个 connect() 函数可以返回任意的 Duplex 流,或
另一个 http.Agent 实例来委托请求,并且可能是
异步的(通过定义 async 功能)。
此代理的实例可以与 http 和 https
模块。中的options参数进行区分 connect()
函数包括 secureEndpoint 属性,该属性可被检查
确定应该返回什么类型的套接字。
一些子类:
下面是一些更有趣的用法 agent-base。
发送一个pull请求来列出你的!
http-proxy-agent: HTTP代理http.AgentHTTP端点的实现https-proxy-agent: HTTP代理http.AgentHTTPS端点的实现pac-proxy-agent: PAC文件代理http.AgentHTTP和HTTPS的实现socks-proxy-agent: SOCKS代理http.AgentHTTP和HTTPS的实现
例子
下面是一个创建new的最小示例 net.Socket 或 tls.Socket
基于 secureEndpoint 财产。这两种药剂都可以使用
这个 http 和 https 模块。
import * as net from 'net';
import * as tls from 'tls';
import * as http from 'http';
import { Agent } from 'agent-base';
class MyAgent extends Agent {
connect(req, opts) {
// `secureEndpoint` is true when using the "https" module
if (opts.secureEndpoint) {
return tls.connect(opts);
} else {
return net.connect(opts);
}
}
});
// Keep alive enabled means that `connect()` will only be
// invoked when a new connection needs to be created
const agent = new MyAgent({ keepAlive: true });
// Pass the `agent` option when creating the HTTP request
http.get('http://nodejs.org/api/', { agent }, (res) => {
console.log('"response" event!', res.headers);
res.pipe(process.stdout);
});