UNPKG

2.46 kBMarkdownView Raw
1agent-base
2==========
3### Turn a function into an [`http.Agent`][http.Agent] instance
4
5This module is a thin wrapper around the base `http.Agent` class.
6
7It provides an abstract class that must define a `connect()` function,
8which is responsible for creating the underlying socket that the HTTP
9client requests will use.
10
11The `connect()` function may return an arbitrary `Duplex` stream, or
12another `http.Agent` instance to delegate the request to, and may be
13asynchronous (by defining an `async` function).
14
15Instances of this agent can be used with the `http` and `https`
16modules. To differentiate, the options parameter in the `connect()`
17function includes a `secureEndpoint` property, which can be checked
18to determine what type of socket should be returned.
19
20#### Some subclasses:
21
22Here are some more interesting uses of `agent-base`.
23Send a pull request to list yours!
24
25 * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints
26 * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints
27 * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS
28 * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS
29
30Example
31-------
32
33Here's a minimal example that creates a new `net.Socket` or `tls.Socket`
34based on the `secureEndpoint` property. This agent can be used with both
35the `http` and `https` modules.
36
37```ts
38import * as net from 'net';
39import * as tls from 'tls';
40import * as http from 'http';
41import { Agent } from 'agent-base';
42
43class MyAgent extends Agent {
44 connect(req, opts) {
45 // `secureEndpoint` is true when using the "https" module
46 if (opts.secureEndpoint) {
47 return tls.connect(opts);
48 } else {
49 return net.connect(opts);
50 }
51 }
52});
53
54// Keep alive enabled means that `connect()` will only be
55// invoked when a new connection needs to be created
56const agent = new MyAgent({ keepAlive: true });
57
58// Pass the `agent` option when creating the HTTP request
59http.get('http://nodejs.org/api/', { agent }, (res) => {
60 console.log('"response" event!', res.headers);
61 res.pipe(process.stdout);
62});
63```
64
65[http-proxy-agent]: ../http-proxy-agent
66[https-proxy-agent]: ../https-proxy-agent
67[pac-proxy-agent]: ../pac-proxy-agent
68[socks-proxy-agent]: ../socks-proxy-agent
69[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent