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:
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
const http = require( 'http' );
var agent = new http.Agent({});
var createConnection = agent.createConnection;
console.log( 'Connection successfully created...' );
console.log( 'Connection: ' , createConnection);
|
Output:
Connection successfully created...
Connection: [Function: connect]
Example 2: Filename: index.js
const http = require( 'http' );
var agent = new http.Agent({});
const aliveAgent = new http.Agent({
keepAlive: true ,
maxSockets: 0, maxSockets: 5,
});
var agent = new http.Agent({});
var createConnection = aliveAgent.createConnection;
var createConnection = agent.createConnection;
console.log( 'Connection successfully created...' );
console.log(createConnection);
console.log( 'Connection successfully created...' );
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