Globalagent

https.globalAgent JavaScript and Node.js code examples

Best JavaScript code snippets using obalAgent(Showing top 10 results out of 315)describe(“#NodeHttpStack”, function () {
it(“should allow to pass options to Node’s requests”, async function () {
const customAgent = new ();
const stack = (new tpStack({
agent: customAgent}));
const req = eateRequest(“GET”, “);
await ();
expect(tUnderlyingObject())(customAgent);
expect(tUnderlyingObject())(obalAgent);});});
(‘/_stats’, (req, res) => {
({: {
sockets: socketStats(ckets),
freeSockets: socketStats(eeSockets), }, : {
freeSockets: socketStats(eeSockets), }, });});
constructor(options){
super();
tpsAgent = obalAgent;
tpAgent = obalAgent;
(options);}
const setupHTTPClient = () => {
if (eCertFile) {
if (Config. certFile! == undefined) {
= [adFileSync(Config. certFile)];
(‘Loaded cert file:’, Config. certFile);}}
epAlive = epAlive;
epAlive = epAlive;}
rEach(userDefinedCAStores, store => {
(adFileSync(store));});
constructor(){
super(guments);
=;
obalAgent = obalAgent;
this. enforceProtocol = ‘:’;}
if (code === ‘200’) {
if (use_secure === ‘disable’) {
xSockets = 1000000;
eateServer(app)({port: usecsebaseport, agent: false}, function () {
(‘mobius server (‘ + dress() + ‘) running at ‘ + usecsebaseport + ‘ port’);
ca: adFileSync(”)};
eateServer(options, app)({port: usecsebaseport, agent: false}, function () {
= [];
epAlive = false;
eCertFile = false;
expect()(0);
setupHTTPClient();
expect()(1);});
expect()(0);});
expect(epAlive);
expect(epAlive);});
epAlive = true;
(‘mobius server (‘ + dress() + ‘) running at ‘ + usecsebaseport + ‘ port’);
global-agent - npm

global-agent – npm

Global HTTP/HTTPS proxy configurable using environment variables.
Usage
Setup proxy using global-agent/bootstrap
Setup proxy using bootstrap routine
Runtime configuration
Exclude URLs
Enable logging
API
createGlobalProxyAgent
Environment variables
OBAL_AGENT
Supported libraries
FAQ
What is the reason global-agent overrides explicitly configured HTTP(S) agent?
What is the reason global-agent/bootstrap does not use HTTP_PROXY?
What is the difference from global-tunnel and tunnel?
To configure HTTP proxy:
Import global-agent/bootstrap.
Export HTTP proxy address as GLOBAL_AGENT_HTTP_PROXY environment variable.
Code:
import ‘global-agent/bootstrap’;
// or:
// import {bootstrap} from ‘global-agent’;
// bootstrap();
Bash:
$ export GLOBAL_AGENT_HTTP_PROXY=
Alternatively, you can preload module using –require, -r configuration, e. g.
$ export GLOBAL_AGENT_HTTP_PROXY=$ node -r ‘global-agent/bootstrap’
Instead of importing a self-initialising script with side-effects as demonstrated in the setup proxy using global-agent/bootstrap documentation, you can import bootstrap routine and explicitly evaluate the bootstrap logic, e. g.
import {
bootstrap} from ‘global-agent’;
bootstrap();
This is useful if you need to conditionally bootstrap global-agent, e. g.
import globalTunnel from ‘global-tunnel-ng’;
const MAJOR_NODEJS_VERSION = parseInt((1)(‘. ‘)[0], 10);
if (MAJOR_NODEJS_VERSION >= 10) {
// `global-agent` works with v10 and above.
bootstrap();} else {
// `global-tunnel-ng` works only with v10 and below.
itialize();}
Setup proxy using createGlobalProxyAgent
If you do not want to use OBAL_AGENT variable, then you can use createGlobalProxyAgent to instantiate a controlled instance of global-agent, e. g.
createGlobalProxyAgent} from ‘global-agent’;
const globalProxyAgent = createGlobalProxyAgent();
Unlike bootstrap routine, createGlobalProxyAgent factory does not create OBAL_AGENT variable and does not guard against multiple initializations of global-agent. The result object of createGlobalProxyAgent is equivalent to OBAL_AGENT.
global-agent/bootstrap script copies value to TP_PROXY and continues to use the latter variable.
You can override the TP_PROXY value at runtime to change proxy behaviour, e. g.
(”);
TP_PROXY = ”;
The first HTTP request is going to use proxy and the secord request is going to use All global-agent configuration is available under OBAL_AGENT namespace.
The GLOBAL_AGENT_NO_PROXY environment variable specifies a pattern of URLs that should be excluded from proxying. GLOBAL_AGENT_NO_PROXY value is a comma-separated list of domain names. Asterisks can be used as wildcards, e. g.
export GLOBAL_AGENT_NO_PROXY=’*, ‘
says to contact all machines with the ” TLD and ” domains directly.
Separate proxy for HTTPS
The environment variable GLOBAL_AGENT_HTTPS_PROXY can be set to specify a separate proxy for HTTPS requests. When this variable is not set GLOBAL_AGENT_HTTP_PROXY is used for both HTTP and HTTPS requests.
global-agent is using roarr logger to log HTTP requests and response (HTTP status code and headers), e. g.
{“context”:{“program”:”global-agent”, “namespace”:”Agent”, “logLevel”:10, “destination”:”, “proxy”:”}, “message”:”proxying request”, “sequence”:1, “time”:1556269669663, “version”:”1. 0. 0″}
{“context”:{“program”:”global-agent”, “namespace”:”Agent”, “logLevel”:10, “headers”:{“content-type”:”text/plain”, “content-length”:”2″, “date”:”Fri, 26 Apr 2019 12:07:50 GMT”, “connection”:”close”}, “requestId”:6, “statusCode”:200}, “message”:”proxying response”, “sequence”:2, “time”:1557133856955, “version”:”1. 0″}
Export ROARR_LOG=true environment variable to enable log printing to stdout.
Use roarr-cli program to pretty-print the logs.
/**
* @property environmentVariableNamespace Defines namespace of `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables. (Default: `GLOBAL_AGENT_`)
* @property forceGlobalAgent Forces to use `global-agent` HTTP(S) agent even when request was explicitly constructed with another agent. (Default: `true`)
* @property socketConnectionTimeout Destroys socket if connection is not established within the timeout. (Default: `60000`)
*/
type ProxyAgentConfigurationInputType = {|
+environmentVariableNamespace? : string,
+forceGlobalAgent? : boolean,
+socketConnectionTimeout? : number,
|};
(configurationInput: ProxyAgentConfigurationInputType) => ProxyAgentConfigurationType;
Name
Description
Default
GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE
Defines namespace of HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.
GLOBAL_AGENT_
GLOBAL_AGENT_FORCE_GLOBAL_AGENT
Forces to use global-agent HTTP(S) agent even when request was explicitly constructed with another agent.
true
GLOBAL_AGENT_SOCKET_CONNECTION_TIMEOUT
Destroys socket if connection is not established within the timeout.
60000
${NAMESPACE}_HTTP_PROXY
Sets the initial proxy controller HTTP_PROXY value.
N/A
${NAMESPACE}_HTTPS_PROXY
Sets the initial proxy controller HTTPS_PROXY value.
${NAMESPACE}_NO_PROXY
Sets the initial proxy controller NO_PROXY value.
OBAL_AGENT is initialized by bootstrap routine.
OBAL_AGENT has the following properties:
Configurable
HTTP_PROXY
Yes
Sets HTTP proxy to use.
HTTPS_PROXY
Sets a distinct proxy to use for HTTPS requests.
NO_PROXY
Specifies a pattern of URLs that should be excluded from proxying. See Exclude URLs.
global-agent works with all libraries that internally use quest.
global-agent has been tested to work with:
got
axios
request
By default, global-agent overrides agent property of any HTTP request, even if agent property was explicitly set when constructing a HTTP request. This behaviour allows to intercept requests of libraries that use a custom instance of an agent per default (e. g. Stripe SDK uses an (s). globalAgent instance pre-configured with keepAlive: true).
This behaviour can be disabled with GLOBAL_AGENT_FORCE_GLOBAL_AGENT=false environment variable. When disabled, then global-agent will only set agent property when it is not already defined or if agent is an instance of (s). globalAgent.
Some libraries (e. request) change their behaviour when HTTP_PROXY environment variable is present. Using a namespaced environment variable prevents conflicting library behaviour.
You can override this behaviour by configuring GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE variable, e. g.
$ export GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE=
Now script initialized using global-agent/bootstrap will use HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.
global-tunnel (including global-tunnel-ng and tunnel) are designed to support legacy versions. They use various workarounds and rely on monkey-patching quest,, quest and methods.
In contrast, global-agent supports v10 and above, and does not implements workarounds for the older versions.
HTTP | Node.js v17.0.1 Documentation

HTTP | Node.js v17.0.1 Documentation

HTTP#
Source Code: lib/
To use the HTTP server and client one must require(”).
The HTTP interfaces in are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.
HTTP message headers are represented by an object like this:
{ ‘content-length’: ‘123’,
‘content-type’: ‘text/plain’,
‘connection’: ‘keep-alive’,
‘host’: ”,
‘accept’: ‘*/*’}
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
See message. headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2,… ]. For
example, the previous message header object might have a rawHeaders
list like the following:
[ ‘ConTent-Length’, ‘123456’,
‘content-LENGTH’, ‘123’,
‘content-type’, ‘text/plain’,
‘CONNECTION’, ‘keep-alive’,
‘Host’, ”,
‘accepT’, ‘*/*’]
Class:
Added in: v0. 3. 4
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the process running when there are no outstanding requests.
(see ()).
It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a ‘close’ event or an ‘agentRemove’ event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
(options, (res) => {
// Do stuff})(‘socket’, (socket) => {
(‘agentRemove’);});
An agent may also be used for an individual request. By providing
{agent: false} as an option to the () or quest()
functions, a one-time use Agent with default options will be used
for the client connection.
agent:false:
({
hostname: ‘localhost’,
port: 80,
path: ‘/’,
agent: false // Create a new agent just for this one request}, (res) => {
// Do stuff with response});
new Agent([options])#
options Set of configurable options to set on the agent.
Can have the following fields:
keepAlive 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. Not to be confused with the
keep-alive value of the Connection header. The Connection: keep-alive
header is always sent when using an agent except when the Connection
header is explicitly specified or when the keepAlive and maxSockets
options are respectively set to false and Infinity, in which case
Connection: close will be used. Default: false.
keepAliveMsecs 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 Maximum number of sockets to allow per host.
If the same host opens multiple concurrent connections, each request
will use new socket until the maxSockets value is reached.
If the host attempts to open more connections than maxSockets,
the additional requests will enter into a pending request queue, and
will enter active connection state when an existing connection terminates.
This makes sure there are at most maxSockets active connections at
any point in time, from a given host.
Default: Infinity.
maxTotalSockets Maximum number of sockets allowed for
all hosts in total. Each request will use a new socket
until the maximum is reached.
maxFreeSockets Maximum number of sockets to leave open
in a free state. Only relevant if keepAlive is set to true.
Default: 256.
scheduling Scheduling strategy to apply when picking
the next free socket to use. It can be ‘fifo’ or ‘lifo’.
The main difference between the two scheduling strategies is that ‘lifo’
selects the most recently used socket, while ‘fifo’ selects
the least recently used socket.
In case of a low rate of request per second, the ‘lifo’ scheduling
will lower the risk of picking a socket that might have been closed
by the server due to inactivity.
In case of a high rate of request per second,
the ‘fifo’ scheduling will maximize the number of open sockets,
while the ‘lifo’ scheduling will keep it as low as possible.
Default: ‘lifo’.
timeout Socket timeout in milliseconds.
This will set the timeout when the socket is created.
options in nnect() are also supported.
The default obalAgent that is used by quest() has all
of these values set to their respective defaults.
To configure any of them, a custom instance must be created.
const = require(”);
const keepAliveAgent = new ({ keepAlive: true});
= keepAliveAgent;
quest(options, onResponseCallback);
eateConnection(options[, callback])#
Added in: v0. 11. 4
options Options containing connection details. Check
eateConnection() for the format of the options
callback Callback function that receives the created socket
Returns: <>
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as eateConnection(). However,
custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to callback.
This method is guaranteed to return an instance of the <> class,
a subclass of <>, unless the user specifies a socket
type other than <>.
callback has a signature of (err, stream).
epSocketAlive(socket)#
Added in: v8. 1. 0
socket <>
Called when socket is detached from a request and could be persisted by the
Agent. Default behavior is to:
tKeepAlive(true, epAliveMsecs);
();
return true;
This method can be overridden by a particular Agent subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
The socket argument can be an instance of <>, a subclass of
<>.
useSocket(socket, request)#
request
Called when socket is attached to request after being persisted because of
the keep-alive options. Default behavior is to:
This method can be overridden by a particular Agent subclass.
stroy()#
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with keepAlive enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.
eeSockets#

An object which contains arrays of sockets currently awaiting use by
the agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and
removed from the array on ‘timeout’.
tName(options)#
options A set of options providing information for name generation
host A domain name or IP address of the server to issue the
request to
port Port of remote server
localAddress Local interface to bind for network connections
when issuing the request
family Must be 4 or 6 if this doesn’t equal undefined.
Returns:
Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
host:port:localAddress or host:port:localAddress:family. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.
xFreeSockets#
Added in: v0. 7

By default set to 256. For agents with keepAlive enabled, this
sets the maximum number of sockets that will be left open in the free
state.
xSockets#
Added in: v0. 6
By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of tName().
xTotalSockets#
Added in: v14. 5. 0, v12. 19. 0
can have open. Unlike maxSockets, this parameter applies across all origins.
quests#
An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.
ckets#
An object which contains arrays of sockets currently in use by the
agent. Do not modify.
Class: ientRequest#
Added in: v0. 17
Extends:
This object is created internally and returned from quest(). It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value),
getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when calling ().
To get the response, add a listener for ‘response’ to the request object.
‘response’ will be emitted from the request object when the response
headers have been received. The ‘response’ event is executed with one
argument which is an instance of comingMessage.
During the ‘response’ event, one can add listeners to the
response object; particularly to listen for the ‘data’ event.
If no ‘response’ handler is added, then the response will be
entirely discarded. However, if a ‘response’ event handler is added,
then the data from the response object must be consumed, either by
calling () whenever there is a ‘readable’ event, or
by adding a ‘data’ handler, or by calling the () method.
Until the data is consumed, the ‘end’ event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
‘process out of memory’ error.
For backward compatibility, res will only emit ‘error’ if there is an
‘error’ listener registered.
does not check whether Content-Length and the length of the
body which has been transmitted are equal or not.
Event: ‘abort’#
Added in: v1. 4. 1Deprecated since: v17. 0. 0
Stability: 0 – Deprecated. Listen for the ‘close’ event instead.
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().
Event: ‘connect’#
Added in: v0. 7. 0
response
head
Emitted each time a server responds to a request with a CONNECT method. If
this event is not being listened for, clients receiving a CONNECT method will
have their connections closed.
This event is guaranteed to be passed an instance of the <> class,
A client and server pair demonstrating how to listen for the ‘connect’ event:
const net = require(‘net’);
const { URL} = require(‘url’);
// Create an HTTP tunneling proxy
const proxy = eateServer((req, res) => {
res. writeHead(200, { ‘Content-Type’: ‘text/plain’});
(‘okay’);});
(‘connect’, (req, clientSocket, head) => {
// Connect to an origin server
const { port, hostname} = new URL(`${}`);
const serverSocket = nnect(port || 80, hostname, () => {
(‘HTTP/1. 1 200 Connection Establishedrn’ +
‘Proxy-agent: rn’ +
‘rn’);
(head);
(clientSocket);
(serverSocket);});});
// Now that proxy is running
(1337, ‘127. 1’, () => {
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: ‘127. 1’,
method: ‘CONNECT’,
path: ”};
const req = quest(options);
(‘connect’, (res, socket, head) => {
(‘got connected! ‘);
// Make a request over an HTTP tunnel
(‘GET / HTTP/1. 1rn’ +
‘Host: rn’ +
‘Connection: closern’ +
(‘data’, (chunk) => {
(String());});
(‘end’, () => {
();});});});
Event: ‘continue’#
Added in: v0. 2
Emitted when the server sends a ‘100 Continue’ HTTP response, usually because
the request contained ‘Expect: 100-continue’. This is an instruction that
the client should send the request body.
Event: ‘information’#
Added in: v10. 0
info
Version
VersionMajor
VersionMinor
statusCode
statusMessage
headers
rawHeaders
Emitted when the server sends a 1xx intermediate response (excluding 101
Upgrade). The listeners of this event will receive an object containing the
HTTP version, status code, status message, key-value headers object,
and array with the raw header names followed by their respective values.
port: 8080,
path: ‘/length_request’};
// Make a request
(‘information’, (info) => {
(`Got information prior to main response: ${atusCode}`);});
101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2. To be notified of 101 Upgrade notices, listen for the
‘upgrade’ event instead.
Event: ‘response’#
Added in: v0. 0
Emitted when a response is received to this request. This event is emitted only
once.
Event: ‘socket’#
Added in: v0. 3
Event: ‘timeout’#
Added in: v0. 8
Emitted when the underlying socket times out from inactivity. This only notifies
that the socket has been idle. The request must be destroyed manually.
See also: tTimeout().
Event: ‘upgrade’#
Added in: v0. 94
Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.
A client server pair demonstrating how to listen for the ‘upgrade’ event.
// Create an HTTP server
const server = eateServer((req, res) => {
(‘upgrade’, (req, socket, head) => {
(‘HTTP/1. 1 101 Web Socket Protocol Handshakern’ +
‘Upgrade: WebSocketrn’ +
‘Connection: Upgradern’ +
(socket); // echo back});
// Now that server is running
// make a request
headers: {
‘Connection’: ‘Upgrade’,
‘Upgrade’: ‘websocket’}};
(‘upgrade’, (res, socket, upgradeHead) => {
(‘got upgraded! ‘);
(0);});});
()#
Added in: v0. 8Deprecated since: v14. 0, v13. 14. 0
Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
request. aborted#

The request. aborted property will be true if the request has
been aborted.
nnection#
Added in: v0. 0Deprecated since: v13. 0
<>
See
([data[, encoding]][, callback])#
data |
encoding
callback
Returns: Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating ‘0rnrn’.
If data is specified, it is equivalent to calling
(data, encoding) followed by (callback).
If callback is specified, it will be called when the request stream
is finished.
stroy([error])#
error Optional, an error to emit with ‘error’ event.
Destroy the request. Optionally emit an ‘error’ event,
and emit a ‘close’ event. Calling this will cause remaining data
See stroy() for further details.
stroyed#
Added in: v14. 0
Is true after stroy() has been called.
See stroyed for further details.
nished#
Added in: v0. 1Deprecated since: v13. 16. 0
The nished property will be true if ()
has been called. () will automatically be called if the
request was initiated via ().
request. flushHeaders()#
Added in: v1. 6. 0
Flushes the request headers.
For efficiency reasons, normally buffers the request headers until
() is called or the first chunk of request data is written. It
then tries to pack the request headers and data into a single TCP packet.
That’s usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. request. flushHeaders() bypasses
the optimization and kickstarts the request.
tHeader(name)#
name
Returns:
Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
tHeader().
tHeader(‘content-type’, ‘text/html’);
tHeader(‘Content-Length’, teLength(body));
tHeader(‘Cookie’, [‘type=ninja’, ‘language=javascript’]);
const contentType = tHeader(‘Content-Type’);
// ‘contentType’ is ‘text/html’
const contentLength = tHeader(‘Content-Length’);
// ‘contentLength’ is of type number
const cookie = tHeader(‘Cookie’);
// ‘cookie’ is of type string[]
tRawHeaderNames()#
Added in: v15. 13. 0, v14. 17. 0
Returns:
Returns an array containing the unique names of the current outgoing raw
headers. Header names are returned with their exact casing being set.
tHeader(‘Foo’, ‘bar’);
tHeader(‘Set-Cookie’, [‘foo=bar’, ‘bar=baz’]);
const headerNames = tRawHeaderNames();
// headerNames === [‘Foo’, ‘Set-Cookie’]
xHeadersCount#
Default: 2000
Limits maximum response headers count. If set to 0, no limit will be applied.
Added in: v0. 0
The request path.
Added in: v0. 97
The request method.
The request host.
otocol#
The request protocol.
moveHeader(name)#
Removes a header that’s already defined into headers object.
moveHeader(‘Content-Type’);
usedSocket#
Added in: v13. 0
Whether the request is send through a reused socket.
When sending request through a keep-alive enabled agent, the underlying socket
might be reused. But if server closes connection at unfortunate time, client
may run into a ‘ECONNRESET’ error.
// Server has a 5 seconds keep-alive timeout by default. createServer((req, res) => {
(‘hellon’);
();})
(3000);
setInterval(() => {
// Adapting a keep-alive agent
(‘localhost:3000’, { agent}, (res) => {
(‘data’, (data) => {
// Do nothing});});}, 5000); // Sending request on 5s interval so it’s easy to hit idle timeout
By marking a request whether it reused socket or not, we can do
automatic error retry base on it.
const agent = new ({ keepAlive: true});
function retriableRequest() {
const req =
//… })
(‘error’, (err) => {
// Check if retry is needed
if (usedSocket && === ‘ECONNRESET’) {
retriableRequest();}});}
retriableRequest();
tHeader(name, value)#
value
Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, tHeader() may return
non-string values. However, the non-string values will be converted to strings
for network transmission.
tHeader(‘Content-Type’, ‘application/json’);
or
tNoDelay([noDelay])#
Added in: v0. 9
noDelay
Once a socket is assigned to this request and is connected
tNoDelay() will be called.
tSocketKeepAlive([enable][, initialDelay])#
enable
initialDelay
tKeepAlive() will be called.
tTimeout(timeout[, callback])#
timeout Milliseconds before a request times out.
callback Optional function to be called when a timeout occurs.
Same as binding to the ‘timeout’ event.
Returns:
tTimeout() will be called.
Added in: v0. 0
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit ‘readable’ events
because of how the protocol parser attaches to the socket.
host: ”, };
const req = (options);
(‘response’, (res) => {
const ip =;
const port =;
(`Your IP address is ${ip} and your source port is ${port}. `);
// Consume response object});
This property is guaranteed to be an instance of the <> class,
a subclass of <>, unless the user specified a socket
request. writableEnded#
Added in: v12. 9. 0
Is true after () has been called. This property
does not indicate whether the data has been flushed, for this use
request. writableFinished instead.
request. writableFinished#
Added in: v12. 0
Is true if all data has been flushed to the underlying system, immediately
before the ‘finish’ event is emitted.
(chunk[, encoding][, callback])#
Added in: v0. 29
chunk |
Returns:
Sends a chunk of the body. This method can be called multiple times. If no
Content-Length is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
Transfer-Encoding: chunked header is added. Calling ()
is necessary to finish sending the request.
The encoding argument is optional and only applies when chunk is a string.
Defaults to ‘utf8’.
The callback argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.
Returns true if the entire data was flushed successfully to the kernel
buffer. Returns false if all or part of the data was queued in user memory.
‘drain’ will be emitted when the buffer is free again.
When write function is called with empty string or buffer, it does
nothing and waits for more input.
Extends: <>
Event: ‘checkContinue’#
request
response
Emitted each time a request with an HTTP Expect: 100-continue is received.
If this event is not listened for, the server will automatically respond
with a 100 Continue as appropriate.
Handling this event involves calling response. writeContinue() if the
client should continue to send the request body, or generating an appropriate
HTTP response (e. g. 400 Bad Request) if the client should not continue to send
the request body.
When this event is emitted and handled, the ‘request’ event will
not be emitted.
Event: ‘checkExpectation’#
Added in: v5. 0
Emitted each time a request with an HTTP Expect header is received, where the
value is not 100-continue. If this event is not listened for, the server will
automatically respond with a 417 Expectation Failed as appropriate.
Event: ‘clientError’#
exception
If a client connection emits an ‘error’ event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection.
Default behavior is to try close the socket with a HTTP ‘400 Bad Request’,
or a HTTP ‘431 Request Header Fields Too Large’ in the case of a
HPE_HEADER_OVERFLOW error. If the socket is not writable or has already
written data it is immediately destroyed.
socket is the object that the error originated from.
();});
(‘clientError’, (err, socket) => {
(‘HTTP/1. 1 400 Bad Requestrnrn’);});
(8000);
When the ‘clientError’ event occurs, there is no request or response
object, so any HTTP response sent, including response headers and payload,
must be written directly to the socket object. Care must be taken to
ensure the response is a properly formatted HTTP response message.
err is an instance of Error with two extra columns:
bytesParsed: the bytes count of request packet that may have parsed
correctly;
rawPacket: the raw packet of current request.
In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of ECONNRESET errors. Before
trying to send data to the socket, it is better to check that it is still
writable.
if ( === ‘ECONNRESET’ ||! socket. writable) {
return;}
Event: ‘close’#
Added in: v0. 4
Emitted when the server closes.
request Arguments for the HTTP request, as it is in
the ‘request’ event
socket <> Network socket between the server and client
head The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTP CONNECT method. If this event is
not listened for, then clients requesting a CONNECT method will have their
connections closed.
After this event is emitted, the request’s socket will not have a ‘data’
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
Event: ‘connection’#
This event is emitted when a new TCP stream is established. socket is
typically an object of type Usually users will not want to
access this event. In particular, the socket will not emit ‘readable’ events
because of how the protocol parser attaches to the socket. The socket can
also be accessed at
This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any Duplex stream can be passed.
If tTimeout() is called here, the timeout will be replaced with
epAliveTimeout when the socket has served a request (if
epAliveTimeout is non-zero).
Event: ‘request’#
Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).
head The first packet of the upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
([callback])#
Added in: v0. 90
Stops the server from accepting new connections. See ().
server. headersTimeout#
Added in: v11. 0, v10. 0
Default: 60000
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
In case of inactivity, the rules defined in server. timeout apply. However,
that inactivity based timeout would still allow the connection to be kept open
if the headers are being sent very slowly (by default, up to a byte per 2
minutes). In order to prevent this, whenever header data arrives an additional
check is made that more than server. headersTimeout milliseconds has not
passed since the connection was established. If the check fails, a ‘timeout’
event is emitted on the server object, and (by default) the socket is destroyed.
See server. timeout for more information on how timeout behavior can be
customized.
Starts the HTTP server listening for connections.
This method is identical to () from
stening#
Added in: v5. 0
Indicates whether or not the server is listening for connections.
Limits maximum incoming headers count. If set to 0, no limit will be applied.
questTimeout#
Added in: v14. 0
Default: 0
Sets the timeout value in milliseconds for receiving the entire request from
the client.
If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.
tTimeout([msecs][, callback])#
msecs Default: 0 (no timeout)
Sets the timeout value for sockets, and emits a ‘timeout’ event on
the Server object, passing the socket as an argument, if a timeout
occurs.
If there is a ‘timeout’ event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server’s ‘timeout’ event, timeouts must be handled
explicitly.
xRequestsPerSocket#
Added in: v16. 10. 0
Requests per socket. Default: 0 (no limit)
The maximum number of requests socket can handle
before closing keep alive connection.
A value of 0 will disable the limit.
When the limit is reached it will set the Connection header value to close,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get 503 Service Unavailable as a response.
server. timeout#
Timeout in milliseconds. Default: 0 (no timeout)
The number of milliseconds of inactivity before a socket is presumed
to have timed out.
A value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.
epAliveTimeout#
Added in: v8. 0
Timeout in milliseconds. Default: 5000 (5 seconds).
The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i. e.,
server. timeout.
A value of 0 will disable the keep-alive timeout behavior on incoming
connections.
A value of 0 makes the server behave similarly to versions prior
to 8. 0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.
Class: rverResponse#
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the ‘request’ event.
Added in: v0. 7
Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).
Event: ‘finish’#
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the operating system for transmission over the network. It
does not imply that the client has received anything yet.
dTrailers(headers)#
This method adds HTTP trailing headers (a header but at the end of the
message) to the response.
Trailers will only be emitted if chunked encoding is used for the
response; if it is not (e. if the request was HTTP/1. 0), they will
be silently discarded.
HTTP requires the Trailer header to be sent in order to
emit trailers, with a list of the header fields in its value. E. g.,
response. writeHead(200, { ‘Content-Type’: ‘text/plain’,
‘Trailer’: ‘Content-MD5’});
(fileData);
dTrailers({ ‘Content-MD5’: ‘7895bf4b8828b55ceaf47747b4bca667’});
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.
Added in: v13. 2. 0
See ().
This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, (), MUST be called on each response.
If data is specified, it is similar in effect to calling
If callback is specified, it will be called when the response stream
Added in: v0. 2Deprecated since: v13. 0
has been called.
response. flushHeaders()#
Flushes the response headers. See also: request. flushHeaders().
Reads out a header that’s already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to tHeader().
tHeader(‘Content-Type’, ‘text/html’);
tHeader(‘Set-Cookie’, [‘type=ninja’, ‘language=javascript’]);
const contentType = tHeader(‘content-type’);
// contentType is ‘text/html’
// contentLength is of type number
const setCookie = tHeader(‘set-cookie’);
// setCookie is of type string[]
tHeaderNames()#
Added in: v7. 0
Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.
const headerNames = tHeaderNames();
// headerNames === [‘foo’, ‘set-cookie’]
tHeaders()#
Returns:
Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.
The object returned by the tHeaders() method does not
prototypically inherit from the JavaScript Object. This means that typical
Object methods such as String(), obj. hasOw

Frequently Asked Questions about globalagent

Leave a Reply

Your email address will not be published. Required fields are marked *

Theme Blog Tales by Kantipur Themes