1 | agent-base
|
2 | ==========
|
3 | ### Turn a function into an [`http.Agent`][http.Agent] instance
|
4 |
|
5 | This module is a thin wrapper around the base `http.Agent` class.
|
6 |
|
7 | It provides an abstract class that must define a `connect()` function,
|
8 | which is responsible for creating the underlying socket that the HTTP
|
9 | client requests will use.
|
10 |
|
11 | The `connect()` function may return an arbitrary `Duplex` stream, or
|
12 | another `http.Agent` instance to delegate the request to, and may be
|
13 | asynchronous (by defining an `async` function).
|
14 |
|
15 | Instances of this agent can be used with the `http` and `https`
|
16 | modules. To differentiate, the options parameter in the `connect()`
|
17 | function includes a `secureEndpoint` property, which can be checked
|
18 | to determine what type of socket should be returned.
|
19 |
|
20 | #### Some subclasses:
|
21 |
|
22 | Here are some more interesting uses of `agent-base`.
|
23 | Send 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 |
|
30 | Example
|
31 | -------
|
32 |
|
33 | Here's a minimal example that creates a new `net.Socket` or `tls.Socket`
|
34 | based on the `secureEndpoint` property. This agent can be used with both
|
35 | the `http` and `https` modules.
|
36 |
|
37 | ```ts
|
38 | import * as net from 'net';
|
39 | import * as tls from 'tls';
|
40 | import * as http from 'http';
|
41 | import { Agent } from 'agent-base';
|
42 |
|
43 | class 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
|
56 | const agent = new MyAgent({ keepAlive: true });
|
57 |
|
58 | // Pass the `agent` option when creating the HTTP request
|
59 | http.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
|