Skip to content
Related Articles

Related Articles

Improve Article

Node.js http.globalAgent Property

  • Difficulty Level : Basic
  • Last Updated : 30 Sep, 2020

The http.globalAgent (Added in v0.5.9) property is an inbuilt property of the ‘http’ module which is used as the default for all HTTP client requests. It is the global instance of Agent.

An Agent 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. 

In order to get a response and a proper result, we need to import ‘http’ module.

Import:

const http = require('http');

Syntax:



http.globalAgent

Parameters: This property does not accept any parameters as mentioned above.

Return Value<http.Agent>: It is responsible for managing connection persistence and reuses for HTTP clients.

The below example illustrates the use of http.globalAgent property in Node.js.

Example 1:  Filename: index.js




// Node.js program to demonstrate the 
// http.globalAgent Method
  
// Importing http module
var http = require('http');
const { globalAgent } = require('http');
  
const PORT = process.env.PORT || 3000;
  
console.log(globalAgent);
  
// Creating http Server
var httpServer = http.createServer(
      function(request, response) {
  
  console.log(globalAgent);
  
  var Output = "Hello Geeksforgeeks..., "
    + "Output of global agent is: " +
  JSON.stringify(globalAgent);
  
  // Prints Output on the browser in response
  response.write(Output);
  response.end('ok');
});
  
// Listening to http Server
httpServer.listen(PORT, ()=>{
   console.log("Server is running at port 3000...");
});

Run index.js file using the following command:

node index.js

Output:

In Console

>> Server is running at port 3000…



Agent { _events: [Object: null prototype] {

   free: [Function (anonymous)],

   newListener: [Function: maybeEnableKeylog]}, _eventsCount: 2,

 _maxListeners: undefined, defaultPort: 80,

 protocol: ‘http:’, options: { path: null },

 requests: {}, sockets: {},

 freeSockets: {}, keepAliveMsecs: 1000,

 keepAlive: false, maxSockets: Infinity,

 maxFreeSockets: 256, scheduling: ‘fifo’,

 maxTotalSockets: Infinity, totalSocketCount: 0,

 [Symbol(kCapture)]: false}

Now run http://localhost:3000/ in the browser.

Output: In Browser

Hello Geeksforgeeks…, global agents are: {“_events”:{}, “_eventsCount”:2, “defaultPort”:80,

“protocol”:”http:”, “options”:{“path”:null}, “requests”:{}, “sockets”:{},

“freeSockets”:{}, “keepAliveMsecs”:1000, “keepAlive”:false, “maxSockets”:null, “maxFreeSockets”:256,

“scheduling”:”fifo”, “maxTotalSockets”:null, “totalSocketCount”:0}ok

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :