### Install Package Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Command to install the package via npm. ```bash npm i agentkeepalive ``` -------------------------------- ### Agentkeepalive Installation Source: https://www.npmjs.com/package/agentkeepalive?activeTab=code Instructions on how to install the agentkeepalive package using npm. ```APIDOC ## Install ```bash $ npm install agentkeepalive --save ``` ``` -------------------------------- ### HTTP Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependents Example demonstrating how to use agentkeepalive with the Node.js http module. ```APIDOC ## HTTP Usage ### Description Example demonstrating how to use agentkeepalive with the Node.js http module. ### Code Example ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const keepaliveAgent = new HttpAgent({ maxSockets: 100, maxFreeSockets: 10, timeout: 60000, // active socket keepalive for 60 seconds freeSocketTimeout: 30000, // free socket keepalive for 30 seconds }); const options = { host: 'cnodejs.org', port: 80, path: '/', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { if (keepaliveAgent.statusChanged) { console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus()); } }, 2000); ``` ``` -------------------------------- ### HTTP Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=code Example demonstrating how to use agentkeepalive with Node.js's http module. ```APIDOC ## Usage ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const keepaliveAgent = new HttpAgent({ maxSockets: 100, maxFreeSockets: 10, timeout: 60000, // active socket keepalive for 60 seconds freeSocketTimeout: 30000, // free socket keepalive for 30 seconds }); const options = { host: 'cnodejs.org', port: 80, path: '/', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { if (keepaliveAgent.statusChanged) { console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus()); } }, 2000); ``` ``` -------------------------------- ### Agentkeepalive Installation Source: https://www.npmjs.com/package/agentkeepalive?activeTab=versions Install the agentkeepalive package using npm. ```APIDOC ## Install ```bash $ npm install agentkeepalive --save ``` ``` -------------------------------- ### HTTP Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=versions Example demonstrating how to use agentkeepalive with the Node.js http module. ```APIDOC ## Usage ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const keepaliveAgent = new HttpAgent({ maxSockets: 100, maxFreeSockets: 10, timeout: 60000, // active socket keepalive for 60 seconds freeSocketTimeout: 30000, // free socket keepalive for 30 seconds }); const options = { host: 'cnodejs.org', port: 80, path: '/', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { if (keepaliveAgent.statusChanged) { console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus()); } }, 2000); ``` ``` -------------------------------- ### HTTPS Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependents Example demonstrating how to use agentkeepalive with the Node.js https module. ```APIDOC ## Support `https` ### Description Example demonstrating how to use agentkeepalive with the Node.js https module. ### Code Example ```javascript const https = require('https'); const HttpsAgent = require('agentkeepalive').HttpsAgent; const keepaliveAgent = new HttpsAgent(); // https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8 const options = { host: 'www.google.com', port: 443, path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8', method: 'GET', agent: keepaliveAgent, }; const req = https.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', chunk => { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { console.log('agent status: %j', keepaliveAgent.getCurrentStatus()); }, 2000); ``` ``` -------------------------------- ### HTTPS Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=versions Example demonstrating how to use agentkeepalive with the Node.js https module. ```APIDOC ### Support `https` ```javascript const https = require('https'); const HttpsAgent = require('agentkeepalive').HttpsAgent; const keepaliveAgent = new HttpsAgent(); // https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8 const options = { host: 'www.google.com', port: 443, path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8', method: 'GET', agent: keepaliveAgent, }; const req = https.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', chunk => { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { console.log('agent status: %j', keepaliveAgent.getCurrentStatus()); }, 2000); ``` ``` -------------------------------- ### HTTPS Usage Example Source: https://www.npmjs.com/package/agentkeepalive?activeTab=code Example demonstrating how to use agentkeepalive with Node.js's https module. ```APIDOC ### Support `https` ```javascript const https = require('https'); const HttpsAgent = require('agentkeepalive').HttpsAgent; const keepaliveAgent = new HttpsAgent(); // https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8 const options = { host: 'www.google.com', port: 443, path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8', method: 'GET', agent: keepaliveAgent, }; const req = https.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', chunk => { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { console.log('agent status: %j', keepaliveAgent.getCurrentStatus()); }, 2000); ``` ``` -------------------------------- ### Install agentkeepalive Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Install the agentkeepalive package using npm. This is a prerequisite for using the package in your Node.js project. ```bash npm install agentkeepalive --save ``` -------------------------------- ### Create and use an HTTPS keep-alive agent Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Demonstrates how to create and use an HttpsAgent for secure HTTPS connections. This example shows making a request to Google, similar to the HTTP example, but using the HttpsAgent. ```javascript const https = require('https'); const HttpsAgent = require('agentkeepalive').HttpsAgent; const keepaliveAgent = new HttpsAgent(); // https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8 const options = { host: 'www.google.com', port: 443, path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8', method: 'GET', agent: keepaliveAgent, }; const req = https.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', chunk => { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { console.log('agent status: %j', keepaliveAgent.getCurrentStatus()); }, 2000); ``` -------------------------------- ### Get current agent status Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Retrieves the current status of the agentkeepalive agent, including counts of created, closed, and timed-out sockets, as well as active requests and socket pools. ```javascript { createSocketCount: 10, closeSocketCount: 5, timeoutSocketCount: 0, requestCount: 5, freeSockets: { 'localhost:57479:': 3 }, sockets: { 'localhost:57479:': 5 }, requests: {} } ``` -------------------------------- ### Agentkeepalive Constructor and Options Source: https://www.npmjs.com/package/agentkeepalive?activeTab=versions Details on how to instantiate the Agent and its configurable options. ```APIDOC ## new Agent([options]) * `options` {Object} Set of configurable options to set on the agent. Can have the following fields: * `keepAlive` {Boolean} Keep sockets around in a pool to be used by other requests in the future. Default = `true`. * `keepAliveMsecs` {Number} When using the keepAlive option, specifies the initial delay for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Defaults to 1000. Default = `1000`. Only relevant if `keepAlive` is set to `true`. * `freeSocketTimeout`: {Number} Sets the free socket to timeout after `freeSocketTimeout` milliseconds of inactivity on the free socket. The default server-side timeout is 5000 milliseconds, to avoid ECONNRESET exceptions, we set the default value to `4000` milliseconds. Only relevant if `keepAlive` is set to `true`. * `timeout`: {Number} Sets the working socket to timeout after `timeout` milliseconds of inactivity on the working socket. Default is `freeSocketTimeout * 2` so long as that value is greater than or equal to 8 seconds, otherwise the default is 8 seconds. * `maxSockets` {Number} Maximum number of sockets to allow per host. Default = `Infinity`. * `maxFreeSockets` {Number} Maximum number of sockets (per host) to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `256`. * `socketActiveTTL` {Number} Sets the socket active time to live, even if it's in use. If not set, the behaviour keeps the same (the socket will be released only when free) Default = `null`. ``` -------------------------------- ### Agentkeepalive Constructor and Options Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependents Details on how to instantiate the Agent and its configurable options. ```APIDOC ## new Agent([options]) ### Description Instantiates a new agent with configurable options. ### Parameters #### Request Body - **options** (Object) - Set of configurable options to set on the agent. - **keepAlive** (Boolean) - Keep sockets around in a pool to be used by other requests in the future. Default = `true`. - **keepAliveMsecs** (Number) - When using the keepAlive option, specifies the initial delay for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Defaults to 1000. Default = `1000`. Only relevant if `keepAlive` is set to `true`. - **freeSocketTimeout** (Number) - Sets the free socket to timeout after `freeSocketTimeout` milliseconds of inactivity on the free socket. The default server-side timeout is 5000 milliseconds, to avoid ECONNRESET exceptions, we set the default value to `4000` milliseconds. Only relevant if `keepAlive` is set to `true`. - **timeout** (Number) - Sets the working socket to timeout after `timeout` milliseconds of inactivity on the working socket. Default is `freeSocketTimeout * 2` so long as that value is greater than or equal to 8 seconds, otherwise the default is 8 seconds. - **maxSockets** (Number) - Maximum number of sockets to allow per host. Default = `Infinity`. - **maxFreeSockets** (Number) - Maximum number of sockets (per host) to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `256`. - **socketActiveTTL** (Number) - Sets the socket active time to live, even if it's in use. If not set, the behaviour keeps the same (the socket will be released only when free) Default = `null`. ``` -------------------------------- ### Constructor new Agent([options]) Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependencies Initializes a new HttpAgent or HttpsAgent instance with configurable connection pooling and timeout settings. ```APIDOC ## new Agent([options]) ### Description Creates a new instance of the agent with specific configuration options for socket management. ### Parameters #### Request Body - **keepAlive** (Boolean) - Optional - Keep sockets around in a pool. Default: true. - **keepAliveMsecs** (Number) - Optional - Initial delay for TCP Keep-Alive packets. Default: 1000. - **freeSocketTimeout** (Number) - Optional - Timeout in ms for inactivity on a free socket. Default: 4000. - **timeout** (Number) - Optional - Timeout in ms for inactivity on a working socket. Default: freeSocketTimeout * 2 (min 8s). - **maxSockets** (Number) - Optional - Maximum number of sockets per host. Default: Infinity. - **maxFreeSockets** (Number) - Optional - Maximum number of sockets to leave open in a free state. Default: 256. - **socketActiveTTL** (Number) - Optional - Socket active time to live. Default: null. ``` -------------------------------- ### Run Benchmark Scripts Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Execute the provided benchmark suite to compare performance. ```bash cd benchmark sh start.sh ``` -------------------------------- ### Create and use an HTTP keep-alive agent Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Demonstrates how to create an instance of HttpAgent with custom options for managing HTTP connections. It shows how to configure socket timeouts and maximum socket counts, and then use this agent with http.request. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const keepaliveAgent = new HttpAgent({ maxSockets: 100, maxFreeSockets: 10, timeout: 60000, // active socket keepalive for 60 seconds freeSocketTimeout: 30000, // free socket keepalive for 30 seconds }); const options = { host: 'cnodejs.org', port: 80, path: '/', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', e => { console.log('problem with request: ' + e.message); }); req.end(); setTimeout(() => { if (keepaliveAgent.statusChanged) { console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus()); } }, 2000); ``` -------------------------------- ### new Agent([options]) Source: https://www.npmjs.com/package/agentkeepalive Constructor for creating a new HttpAgent or HttpsAgent instance with configurable connection pooling and timeout settings. ```APIDOC ## new Agent([options]) ### Description Initializes a new agent instance to manage HTTP/HTTPS connection pooling. ### Parameters #### Request Body - **keepAlive** (Boolean) - Optional - Keep sockets around in a pool. Default = true. - **keepAliveMsecs** (Number) - Optional - Initial delay for TCP Keep-Alive packets. Default = 1000. - **freeSocketTimeout** (Number) - Optional - Timeout in ms for inactivity on a free socket. Default = 4000. - **timeout** (Number) - Optional - Timeout in ms for inactivity on a working socket. - **maxSockets** (Number) - Optional - Maximum number of sockets per host. Default = Infinity. - **maxFreeSockets** (Number) - Optional - Maximum number of sockets to leave open in a free state. Default = 256. - **socketActiveTTL** (Number) - Optional - Socket active time to live. Default = null. ``` -------------------------------- ### new Agent([options]) Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Constructor for creating a new HttpAgent or HttpsAgent instance with configurable connection pooling and timeout settings. ```APIDOC ## new Agent([options]) ### Description Initializes a new agent instance to manage HTTP/HTTPS connections with keep-alive enabled by default. ### Parameters #### Request Body - **keepAlive** (Boolean) - Optional - Keep sockets around in a pool. Default: true. - **keepAliveMsecs** (Number) - Optional - Initial delay for TCP Keep-Alive packets. Default: 1000. - **freeSocketTimeout** (Number) - Optional - Timeout in ms for inactivity on a free socket. Default: 4000. - **timeout** (Number) - Optional - Timeout in ms for inactivity on a working socket. - **maxSockets** (Number) - Optional - Maximum number of sockets per host. Default: Infinity. - **maxFreeSockets** (Number) - Optional - Maximum number of free sockets per host. Default: 256. - **socketActiveTTL** (Number) - Optional - Socket active time to live in ms. ``` -------------------------------- ### Socket Creation Metrics Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Detailed socket lifecycle and latency distribution data. ```json [proxy.js:120000] keepalive, 50 created, 60000 requestFinished, 1200 req/socket, 0 requests, 0 sockets, 0 unusedSockets, 50 timeout {" <10ms":662," <15ms":17825," <20ms":20552," <30ms":17646," <40ms":2315," <50ms":567," <100ms":377," <150ms":56," <200ms":0," >=200ms+":0} ---------------------------------------------------------------- [proxy.js:120000] normal , 53866 created, 84260 requestFinished, 1.56 req/socket, 0 requests, 0 sockets {" <10ms":75," <15ms":1112," <20ms":10947," <30ms":32130," <40ms":8228," <50ms":3002," <100ms":4274," <150ms":181," <200ms":18," >=200ms+":33} ``` -------------------------------- ### Benchmark Results Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Performance metrics for the keep-alive agent compared to a normal agent. ```text Transactions: 60000 hits Availability: 100.00 % Elapsed time: 29.70 secs Data transferred: 14.88 MB Response time: 0.03 secs Transaction rate: 2020.20 trans/sec Throughput: 0.50 MB/sec Concurrency: 59.84 Successful transactions: 60000 Failed transactions: 0 Longest transaction: 0.15 Shortest transaction: 0.01 ``` ```text Transactions: 60000 hits Availability: 100.00 % Elapsed time: 46.53 secs Data transferred: 14.88 MB Response time: 0.05 secs Transaction rate: 1289.49 trans/sec Throughput: 0.32 MB/sec Concurrency: 59.81 Successful transactions: 60000 Failed transactions: 0 Longest transaction: 0.45 Shortest transaction: 0.00 ``` -------------------------------- ### Agent Status Properties and Methods Source: https://www.npmjs.com/package/agentkeepalive?activeTab=code Information about accessing the status of the agentkeepalive instance. ```APIDOC ### `getter agent.statusChanged` counters have change or not after last checkpoint. ### `agent.getCurrentStatus()` `agent.getCurrentStatus()` will return a object to show the status of this agent: ```json { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` ``` -------------------------------- ### Agent Status Properties and Methods Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependents Information about accessing the agent's status. ```APIDOC ### `getter agent.statusChanged` #### Description Indicates if the agent's counters have changed since the last checkpoint. ### `agent.getCurrentStatus()` #### Description Returns an object detailing the current status of the agent. #### Response Example ```json { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` ``` -------------------------------- ### Agent Status Properties and Methods Source: https://www.npmjs.com/package/agentkeepalive?activeTab=versions Information about accessing the agent's status. ```APIDOC ### `getter agent.statusChanged` counters have change or not after last checkpoint. ### `agent.getCurrentStatus()` `agent.getCurrentStatus()` will return a object to show the status of this agent: ```json { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` ``` -------------------------------- ### agent.getCurrentStatus() Source: https://www.npmjs.com/package/agentkeepalive?activeTab=dependencies Retrieves the current status and metrics of the agent instance. ```APIDOC ## agent.getCurrentStatus() ### Description Returns an object containing the current metrics of the agent, including socket counts and active request information. ### Response #### Success Response (200) - **createSocketCount** (Number) - Total sockets created. - **closeSocketCount** (Number) - Total sockets closed. - **timeoutSocketCount** (Number) - Total sockets timed out. - **requestCount** (Number) - Total requests processed. - **freeSockets** (Object) - Map of free sockets per host. - **sockets** (Object) - Map of active sockets per host. - **requests** (Object) - Map of pending requests. #### Response Example { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` -------------------------------- ### agent.getCurrentStatus() Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Retrieves the current status and metrics of the agent instance. ```APIDOC ## agent.getCurrentStatus() ### Description Returns an object containing the current metrics and socket counts for the agent instance. ### Response #### Success Response (200) - **createSocketCount** (Number) - Total sockets created. - **closeSocketCount** (Number) - Total sockets closed. - **timeoutSocketCount** (Number) - Total sockets timed out. - **requestCount** (Number) - Total requests processed. - **freeSockets** (Object) - Map of free sockets per host. - **sockets** (Object) - Map of active sockets per host. - **requests** (Object) - Map of pending requests. #### Response Example { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` -------------------------------- ### agent.getCurrentStatus() Source: https://www.npmjs.com/package/agentkeepalive Retrieves the current status and metrics of the agent instance. ```APIDOC ## agent.getCurrentStatus() ### Description Returns an object containing the current metrics and socket status of the agent. ### Response #### Success Response (200) - **createSocketCount** (Number) - Total sockets created. - **closeSocketCount** (Number) - Total sockets closed. - **timeoutSocketCount** (Number) - Total sockets timed out. - **requestCount** (Number) - Total requests made. - **freeSockets** (Object) - Map of free sockets per host. - **sockets** (Object) - Map of active sockets per host. - **requests** (Object) - Map of pending requests. #### Response Example { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` -------------------------------- ### Handle ECONNRESET with req.reusedSocket Source: https://www.npmjs.com/package/agentkeepalive?activeTab=readme Use req.reusedSocket to detect if a request failed on a reused connection, enabling safe retry logic for keep-alive race conditions. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const agent = new HttpAgent(); const req = http .get('http://localhost:3000', { agent }, (res) => { // ... }) .on('error', (err) => { if (req.reusedSocket && err.code === 'ECONNRESET') { // retry the request or anything else... } }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.