You can create a custom agent by extending the Agent class from agent-base. This is useful for implementing custom socket logic, such as choosing between net.connect and tls.connect based on the endpoint security.
In the connect(req, opts) method:
- Use
opts.secureEndpoint to determine if the connection should be encrypted (HTTPS). - Return a
net.Socket, tls.Socket, or any Duplex stream. - You can also return another
http.Agent to delegate the connection.
Once instantiated, pass the agent to the agent option in Node.js http.get, https.get, or other request methods.
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);
});