Open In App

Node.js new Agent() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ‘require(‘http’)‘). HTTP message headers are represented as JSON Format.

The new Agent({}) (Added in v0.3.4) method is an inbuilt application programming interface (API) of the ‘http’ module in which default globalAgent is used by http.request() which should create a custom http.Agent instance.

Syntax:

new Agent({options})

Parameters: This function accepts a single object parameter as mentioned above and described below:

options <Object> It is the configurable options that could be set on the agent.

  • keepAlive <boolean>: The Default value set is false. It still Keeps the sockets around whether there are outstanding requests or not, so it could be used for future requests without re-establishing the connection (TCP). The keep-alive header connection is sent while using an agent, and a ‘close’ connection is used to close the connection.
  • keepAliveMsecs <number>: The Default value set is false. It denotes the initial delay for TCP Keep-Alive packets and if the keepAlive option is false or undefined, gets ignored.
  • maxSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets per host and until the maximum is reached, each request uses a new socket.
  • maxTotalSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets for all hosts in total and until the maximum is reached, each request uses a new socket.
  • maxFreeSockets <number>: The Default value set is 256. In order to leave open in a free state, it uses the maximum number of sockets and it is relevant only if keepAlive is set to true.
  • scheduling <string>: The Default scheduling is FIFO. It is a strategy of picking the next free socket to schedule and use. It is of two type ‘FIFO‘ or ‘LIFO‘. ‘LIFO‘ (Last In First Out) selects the socket which is most recently used, while ‘FIFO’ (First In First Out) selects the socket which is least recently used.
  • timeout <number>: It counts the socket timeout in milliseconds and sets the timeout when the socket is created.

The below examples illustrate the use of new Agent({}) method in Node.js.

Example 1: Filename: index.js




// Node.js program to demonstrate the 
// new agent({}) method 
  
// Importing http module
const http = require('http');
var agent = new http.Agent({});
  
// Creating new agent
const aliveAgent = new http.Agent({ keepAlive: true
maxSockets: 0, maxSockets: 5,  });
  
// Creating new agent
var agent = new http.Agent({});
  
// Creating new connection
var createConnection = aliveAgent.createConnection;
  
// Creating new connection
var createConnection = agent.createConnection;
console.log('Connection successfully created...');
  
// Printing the connection
console.log(createConnection);
console.log('Connection successfully created...');
  
// Printing the connection
console.log('Connection: ', createConnection);


Run index.js file using the following command:

node index.js

Output:

Connection successfully created…

[Function: connect]

Connection successfully created…

Connection:  [Function: connect]

Another Module agentkeepalive fits better compatible with Http, which makes it easier to handle requests. In order to use the ‘agentkeepalive’ module, we need to install the NPM (Node Package Manager) and the following (on cmd).

// Creates package.json file
>> npm init 

// Installs express module
>> npm install agentkeepalive --save   OR
>> npm i agentkeepalive -s 

Import agentkeepalive module: Import agentkeepalive module and store returned instance into a variable.

const Agent = require('agentkeepalive');

Example 2: Filename: index.js




// Node.js program to demonstrate the 
// new agent({}) method 
  
// Importing http module
const http = require('http');
// Importing agentkeepalive module
const Agent = require('agentkeepalive');
// Creating new agent
const keepAliveAgent = new Agent({});
  
// Options object
const options = {
  host: 'geeksforgeeks.org',
  port: 80,
  path: '/',
  method: 'GET',
  agent: keepAliveAgent,
};
  
// Requesting via http server module
const req = http.request(options, (res) => {
  // console.log(require('util').inspect(res, depth=0));
  // Printing statuscode
  console.log("StatusCode: ", res.statusCode);
  // Printing headers
  console.log("Headers: ", res.headers);
});
  
// Printing agent options
console.log("Agent Options: ", req.agent.options);
// console.log(req.agent.sockets);
req.end();


Run index.js file using the following command:

node index.js

Output:

>> Agent Options: { keepAlive: true,

 freeSocketTimeout: 15000,

 timeout: 30000,

 socketActiveTTL: 0,

 path: null}

>> StatusCode:  301

>> Headers:  { date: ‘Wed, 19 Aug 2020 11:19:23 GMT’,

 server: ‘Apache’,

 location: ‘https://www.geeksforgeeks.org/’,

 ‘content-length’: ‘238’,

 ‘keep-alive’: ‘timeout=5, max=100’,

 connection: ‘Keep-Alive’,

 ‘content-type’: ‘text/html; charset=iso-8859-1’}

Reference: https://nodejs.org/api/http.html#http_new_agent_options



Last Updated : 26 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads