Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js agent.createConnection() Method
Next article icon

Node.js new Agent() Method

Last Updated : 26 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
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



Next Article
Node.js agent.createConnection() Method
author
amitkumarjee
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-HTTP-Module
  • Node.js-Methods

Similar Reads

    http.Agent Method

    • Node.js new Agent() Method
      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 applicat
      4 min read

    • Node.js agent.createConnection() Method
      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 agent.createConnection() (Added in v0.11.4) method is an inbu
      2 min read

    • Node.js agent.maxSockets Method
      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 agent.maxSockets (Added in v0.3.6) method is an inbuilt appli
      2 min read

    • Node.js agent.maxFreeSockets Method
      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 agent.maxFreeSockets (Added in v0.11.7) method is an inbuilt
      2 min read

    http.Server Properties

    • Node.js http.ClientRequest.connection Property
      The http.ClientRequest.connection is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to get the reference of underlying client request socket. Syntax: const request.connectionParameters: It does not accept any argument as the parameter. Return
      2 min read

    • Node.js http.ClientRequest.aborted Property
      The http.ClientRequest.aborted is an inbuilt application programming interface of class Client Request within http module which is used to check if the client request has been aborted or not. Syntax: request.aborted Parameters: It does not accept any argument as a parameter. Return Value: It does no
      2 min read

    • Node.js http.ClientRequest.path Property
      The http.ClientRequest.path is an inbuilt application programming interface of class ClientRequest within HTTP module which is used to get the request path for the particular client request. Syntax: request.pathParameters: This property does not accept any argument as a parameter. Return Value: This
      2 min read

    • Node.js http.ClientRequest.reusedSocket Property
      The http.ClientRequest.reusedSocket is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to check if the request is sent through a reused socket. Syntax: const request.reusedSocketParameters: This property does not accept any argument as a param
      2 min read

    • Node.js http.ClientRequest.socket Property
      The http.ClientRequest.socket is an inbuilt application programming interface of class ClientRequest within HTTP module which is used to get a Proxy object that acts as a net.Socket. Syntax: request.socketParameters: This property does not accept any argument as a parameter. Return Value: This prope
      2 min read

    http.Server Methods

    • Node.js http.ClientRequest.abort() Method
      The http.ClientRequest.abort() is an inbuilt application programming interface of class Client Request within http module which is used to abort the client request. Syntax: ClientRequest.abort() Parameters: This method does not accept any argument as a parameter. Return Value: This method does not r
      2 min read

    • Node.js http.ClientRequest.protocol Method
      The http.ClientRequest.protocol is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to get the object of client request protocol. Syntax: const request.protocolParameters: This function does not accept any argument as a parameter. Return Value:
      2 min read

    • Node.js http.ClientRequest.setNoDelay() Method
      The http.ClientRequest.setNoDelay() is an inbuilt application programming interface of class ClientRequest within HTTP module which is used to set the socket such as delaying of excessive requests while requests are being limited is not desired. Syntax: const request.setNoDelay([noDelay])Parameters:
      2 min read

    • Node.js http.ClientRequest.removeHeader() Method
      The http.ClientRequest.removeHeader() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to remove a header that's already defined into the headers object. Syntax: const request.removeHeader(name)Parameters: This method takes the name of the h
      2 min read

    • Node.js http.ClientRequest.setHeader() Method
      The http.ClientRequest.setHeader() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the object of the header. Syntax: const request.setHeader(name, value)Parameters: This method takes the name and value of the particular header as a p
      2 min read

    • Node.js http.ClientRequest.setTimeout() Method
      The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request. Syntax: request.setTimeout(timeout[, callback])Parameters: This method takes the time out value as a par
      2 min read

    http.Serverv Properties

    • Node.js http.server.timeout Property
      The http.server.timeout is an inbuilt application programming interface of class Server within the HTTP module which is used to get the default Timeout value in milliseconds. In Node.js, the default server timeout is 0 milliseconds for the latest version and 2min i.e. (120000 milliseconds) for the o
      3 min read

    • Node.js http.server.maxHeadersCount Property
      The http.server.maxHeadersCount is an inbuilt application programming interface of class Server within the HTTP module which is used to get the maximum number of incoming headers to count. Syntax: const server.maxHeadersCountParameters: This property does not accept any argument as a parameter. Retu
      3 min read

    • Node.js http.server.listening Property
      The http.server.listening is an inbuilt application programming interface of class Server within http module which is used to check if the server is listening for connection or not. Syntax: const server.listening Parameters: It does not accept any argument as a parameter. Return Value: It does not r
      3 min read

    • Node.js http.server.keepAliveTimeout Property
      The http.server.keepAliveTimeout is an inbuilt application programming interface of class Server within http module which is used to get the number of milliseconds of inactivity a server needs to wait for additional incoming data. Syntax: server.keepAliveTimeout Parameters: This API does not accept
      3 min read

    http.Server Methods

    • Node.js http.server.close() Method
      The http.server.close() is an inbuilt application programming interface of class Server within the HTTP module which is used to stop the server from accepting new connections. Syntax: const server.close([callback])Parameters: This method accepts only one optional callback function argument as a para
      2 min read

    • Node.js http.server.headersTimeout Method
      The http.server.headersTimeout is an inbuilt application programming interface of class Server within the HTTP module which is used to get the time the parser will wait to receive the complete HTTP headers. Syntax: server.headersTimeoutParameters: This method does not accept any arguments as a param
      2 min read

    • Node.js http.server.listen() Method
      The http.server.listen() is an inbuilt application programming interface of the class Server within the HTTP module which is used to start the server by accepting new connections. Syntax: const server.listen(options[, callback])Parameters: This method accepts the following two parameters: option: It
      2 min read

    http.ServerResponse Properties

    • Node.js http.ServerResponse.writableEnded Property
      The httpServerResponse.writableEnded is an inbuilt application programming interface of class Server Response within http module which is used to check if response.end() has been called or not. Syntax: response.writableEnded Parameters: This method does not accept any parameter. Return Value: This m
      2 min read

    • Node.js http.ServerResponse.statusCode Property
      The httpServerResponse.statusCode is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to this property controls the status code that will be sent to the client when the headers get flushed. Syntax: const response.statusCodeParameters: This pro
      2 min read

    • Node.js http.ServerResponse.headersSent Property
      The httpServerResponse.headersSent is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to check if the header has been sent or not. Syntax: const response.headersSentParameters: This property does not accept any arguments as a parameter. Retur
      2 min read

    • Node.js http.ServerResponse.statusMessage Property
      The httpServerResponse.statusMessage is an inbuilt application programming interface of class ServerResponse within http module which is used to control the status message that will be sent to the client when the headers get flushed. Syntax: response.statusMessage Parameters: This method does not ac
      2 min read

    http.ServerResponse Methods

    • Node.js http.ServerResponse.writeProcessing() Method
      The httpServerResponse.writeProcessing() is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to send an HTTP/1.1 102 Processing message to the client. Syntax: response.writeProcessing()Parameters: This method does not accept any arguments as a
      2 min read

    • Node.js http.ServerResponse.sendDate Method
      The httpServerResponse.sendDate is an inbuilt application programming interface of class Server Response within http module which is used to check if the date header has been sent or not. HTTP header is also used to pass additional information such as Date etc. Refer to this article. Syntax: respons
      2 min read

    • Node.js http.ServerResponse.end() Method
      The httpServerResponse.end() is an inbuilt application programming interface of class Server Response within http module which is used to send the signal to the server that all the header has been sent. Syntax: response.end(data, Encodingtype, Callbackfunction) Parameters: This method takes three Pa
      2 min read

    • Node.js http.ServerResponse.connection Method
      The httpServerResponse.connection is an inbuilt application programming interface of class Server Response within http module which is used to get the response socket of this HTTP connection. Syntax: response.connection Parameters: This method does not accept any argument as a parameter. Return Valu
      2 min read

    http.IncomingMessage Methods

    • Node.js http.IncomingMessage.trailers Method
      The http.IncomingMessage.trailers is an inbuilt application programming interface of the class Incoming Message within http module which is used to get the request/response trailers to object. Syntax: request.trailers or response.trailers Parameters: This method does not accept any argument as a par
      2 min read

    • Node.js http.IncomingMessage.statusMessage Method
      The http.IncomingMessage.statusMessage is an inbuilt application programming interface of the class Incoming Message within http module which is used to get the HTTP response status message. Syntax: message.statusMessage Parameters: This method does not accept any argument as a parameter. Return Val
      2 min read

    • Node.js http.IncomingMessage.method Method
      The http.IncomingMessage.method is an inbuilt application programming interface of class Incoming Message within the inbuilt http module which is used to get the type of request method as a string. Syntax: request.method Parameters: This method does not accept any argument as a parameter. Return Val
      2 min read

    • Node.js http.IncomingMessage.rawHeaders Method
      The http.IncomingMessage.rawHeaders is an inbuilt application programming interface of class Incoming Message within http module which is used to get the raw request/response headers to list exactly as they were received. Syntax: request.rawHeaders Parameters: This method does not accept any argumen
      2 min read

    • Node.js http.IncomingMessage.statusCode Method
      The http.IncomingMessage.statusCode is an inbuilt application programming interface of class IncomingMessage within HTTP module which is used to get the 3-digit HTTP response status code. Syntax: const message.statusCodeParameters: This method does not accept any argument as a parameter. Return Valu
      2 min read

    • Node.js http.IncomingMessage.rawTrailers Method
      The http.IncomingMessage.rawTrailers is an inbuilt application programming interface of class IncomingMessage within HTTP module which is used to get the raw request/response trailer keys and values exactly as they were received. Syntax: const message.rawTrailersParameters: This method does not acce
      2 min read

    • Node.js http.IncomingMessage.aborted Method
      The http.IncomingMessage.aborted is an inbuilt application programming interface of class IncomingMessage within the HTTP module which is used to check if the request has been aborted or not. Syntax: const message.abortedParameters: This method does not accept any argument as a parameter. Return Val
      2 min read

    • Node.js http.IncomingMessage.headers Method
      The http.IncomingMessage.headers is an inbuilt application programming interface of class IncomingMessage within the HTTP module which is used to get all the request/response headers objects. Syntax: const message.headersParameters: This method does not accept any argument as a parameter. Return Val
      2 min read

    • Node.js http.IncomingMessage.httpVersion Method
      The http.IncomingMessage.httpVersion is an inbuilt application programming interface of the class Incoming Message within http module which is used to get the HTTP version sent by the client. The most commonly used version is HTTP/1.1. Syntax: request.httpVersion Parameters: This method does not acc
      2 min read

    • Node.js http.IncomingMessage.complete Method
      The http.IncomingMessage.complete is an inbuilt application programming interface of class IncomingMessage within http module which is used to check if a complete HTTP message has been received and successfully parsed or not. Syntax: const message.complete Parameters: This method does not accept any
      2 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences