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 inbuilt application programming interface of the ‘Http‘ module which is used to produce socket or stream which is further used for HTTP requests and by default, it is quite same as net.createConnection(). It returns an instance of the <net.Socket> class, which is a subclass of <stream.Duplex>. A socket or stream can be supplied either by returning the socket/stream from this function or by passing the socket/stream to the callback.
Syntax:
agent.createConnection(options[, callback])
Parameters: This function accepts two parameters as mentioned above and described below:
-
options <Object>: It is any <Object> or JSON data which contains connection details.
-
Callback <Function>: It is a callback<function> which receives the created socket.
Return Value <stream.Duplex>: It returns the duplex stream which is both readable and writable.
Below examples illustrate the use of agent.createConnection(options[, callback]) method in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // agent.createConnection() method // Importing http module const http = require( 'http' ); // Creating new agent var agent = new http.Agent({}); // Creating new connection var createConnection = agent.createConnection; console.log( 'Connection successfully created...' ); // Printing that connection console.log( 'Connection: ' , createConnection); |
Output:
Connection successfully created... Connection: [Function: connect]
Example 2: Filename: index.js
// Node.js program to demonstrate the // agent.createConnection() 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... Connection: [Function: connect] Connection successfully created... Connection: [Function: connect]
Reference: https://nodejs.org/api/http.html#http_agent_createconnection_options_callback
Contact Us