### Agentkeepalive Usage Example Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md A practical example demonstrating how to use the HttpAgent in a Node.js application. ```APIDOC ## Usage Example ### Description Demonstrates how to integrate `agentkeepalive` with Node.js's `http` module for making requests. ### Code ```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); ``` ``` -------------------------------- ### Install agentkeepalive via NPM Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Command to install the agentkeepalive package into your Node.js project as a dependency. ```bash npm install agentkeepalive --save ``` -------------------------------- ### Support HTTPS Requests with Agentkeepalive Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Demonstrates how to use agentkeepalive's HttpsAgent to manage keep-alive connections for HTTPS requests. It shows setting up the agent, configuring request options, making the request, and logging the response status and body. The example also shows how to check the agent's status after a delay. ```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); ``` -------------------------------- ### Retrieve Agent Status Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Example of the object structure returned by the agent.getCurrentStatus() method, showing socket counts and current pool state. ```json { "createSocketCount": 10, "closeSocketCount": 5, "timeoutSocketCount": 0, "requestCount": 5, "freeSockets": { "localhost:57479:": 3 }, "sockets": { "localhost:57479:": 5 }, "requests": {} } ``` -------------------------------- ### Initialize and use HttpAgent Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Demonstrates how to import and configure an HttpAgent with custom socket settings and use it within an http.request call. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const keepaliveAgent = new HttpAgent({ maxSockets: 100, maxFreeSockets: 10, timeout: 60000, freeSocketTimeout: 30000, }); const options = { host: 'cnodejs.org', port: 80, path: '/', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS: ' + res.statusCode); 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(); ``` -------------------------------- ### Agentkeepalive Constructor and Options Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Details on how to instantiate the HttpAgent and its configurable options. ```APIDOC ## new Agent([options]) ### Description Creates a new instance of the enhanced HTTP agent. ### Method `new Agent([options])` ### Parameters #### Options Object - **keepAlive** (Boolean) - Optional - Keep sockets around in a pool to be used by other requests in the future. Default = `true`. - **keepAliveMsecs** (Number) - Optional - 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. Only relevant if `keepAlive` is set to `true`. - **freeSocketTimeout** (Number) - Optional - Sets the free socket to timeout after `freeSocketTimeout` milliseconds of inactivity on the free socket. The default is 4000 milliseconds. Only relevant if `keepAlive` is set to `true`. - **timeout** (Number) - Optional - Sets the working socket to timeout after `timeout` milliseconds of inactivity on the working socket. Default is `freeSocketTimeout * 2` (min 8 seconds). - **maxSockets** (Number) - Optional - Maximum number of sockets to allow per host. Default = `Infinity`. - **maxFreeSockets** (Number) - Optional - 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) - Optional - Sets the socket active time to live, even if it's in use. If not set, the socket will be released only when free. Default = `null`. ``` -------------------------------- ### Run Benchmark Script Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Provides instructions on how to execute the benchmark script for agentkeepalive. This involves navigating to the benchmark directory and running a shell script. The output of the benchmark compares the performance of agentkeepalive against the default Node.js http agent. ```bash cd benchmark sh start.sh ``` -------------------------------- ### Create HTTP Agent with Keep-Alive in Node.js Source: https://context7.com/node-modules/agentkeepalive/llms.txt Demonstrates how to instantiate an HttpAgent from the agentkeepalive library with custom configurations for keep-alive, socket limits, and various timeouts. This agent can then be used with Node.js's http.request to manage HTTP connections efficiently. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; // Create agent with custom configuration const keepaliveAgent = new HttpAgent({ keepAlive: true, // Keep sockets around for future requests (default: true) maxSockets: 100, // Maximum sockets per host (default: Infinity) maxFreeSockets: 10, // Maximum free sockets per host (default: 256) timeout: 60000, // Active socket timeout in ms (default: freeSocketTimeout * 2 or 8000ms) freeSocketTimeout: 30000, // Free socket timeout in ms (default: 4000ms) keepAliveMsecs: 1000, // TCP Keep-Alive initial delay (default: 1000ms) socketActiveTTL: 120000, // Socket max TTL even if in use (default: null - no limit) }); const options = { host: 'api.example.com', port: 80, path: '/users', method: 'GET', agent: keepaliveAgent, }; const req = http.request(options, res => { console.log('STATUS:', res.statusCode); console.log('HEADERS:', JSON.stringify(res.headers)); let body = ''; res.setEncoding('utf8'); res.on('data', chunk => { body += chunk; }); res.on('end', () => { console.log('BODY:', body); console.log('Agent Status:', keepaliveAgent.getCurrentStatus()); }); }); req.on('error', e => { console.error('Request failed:', e.message); }); req.end(); ``` -------------------------------- ### Integrate Agents with http.get and https.get Source: https://context7.com/node-modules/agentkeepalive/llms.txt Shows how to pass HttpAgent and HttpsAgent instances into standard Node.js request methods to enable keep-alive functionality. ```javascript const http = require('http'); const https = require('https'); const { HttpAgent, HttpsAgent } = require('agentkeepalive'); const httpAgent = new HttpAgent(); const httpsAgent = new HttpsAgent(); http.get('http://httpbin.org/ip', { agent: httpAgent }, res => { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => { console.log('HTTP Response:', JSON.parse(data)); console.log('HTTP Agent sockets:', httpAgent.getCurrentStatus().freeSockets); }); }).on('error', e => console.error('HTTP Error:', e.message)); https.get('https://httpbin.org/ip', { agent: httpsAgent }, res => { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => { console.log('HTTPS Response:', JSON.parse(data)); console.log('HTTPS Agent sockets:', httpsAgent.getCurrentStatus().freeSockets); }); }).on('error', e => console.error('HTTPS Error:', e.message)); ``` -------------------------------- ### Agentkeepalive Status Properties and Methods Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Information about accessing the status and changes within the agent. ```APIDOC ## Agent Status ### `getter agent.statusChanged` #### Description Indicates whether 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": {} } ``` ``` -------------------------------- ### Access Internal Library Constants Source: https://context7.com/node-modules/agentkeepalive/llms.txt Explains how to access exported Symbol constants used for tracking socket metadata, useful for advanced debugging and monitoring. ```javascript const { HttpAgent, constants } = require('agentkeepalive'); console.log('Available constants:', Object.keys(constants)); ``` -------------------------------- ### Configure Socket Active TTL for Node.js Source: https://context7.com/node-modules/agentkeepalive/llms.txt Demonstrates how to use the socketActiveTTL option to force socket refresh after a specific duration. This is essential for preventing issues with load balancers that terminate long-lived connections. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const agent = new HttpAgent({ keepAlive: true, maxSockets: 10, maxFreeSockets: 5, freeSocketTimeout: 30000, timeout: 60000, socketActiveTTL: 120000, }); async function longRunningOperations() { const makeRequest = () => { return new Promise((resolve, reject) => { const req = http.get({ host: 'httpbin.org', path: '/get', agent: agent, }, res => { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => resolve(res.statusCode)); }); req.on('error', reject); }); }; for (let i = 0; i < 10; i++) { const status = await makeRequest(); console.log(`Request ${i + 1}: status=${status}`); console.log('Socket stats:', { created: agent.createSocketCount, closed: agent.closeSocketCount, timeout: agent.timeoutSocketCount, }); await new Promise(r => setTimeout(r, 15000)); } } longRunningOperations().catch(console.error); ``` -------------------------------- ### Handle ECONNRESET with Reused Sockets Source: https://github.com/node-modules/agentkeepalive/blob/master/README.md Illustrates how to use the `req.reusedSocket` property to detect if a request was sent over a reused socket, which is crucial for handling `ECONNRESET` errors that can occur during keep-alive race conditions. This allows for automatic retries or other error recovery mechanisms. This functionality is consistent with Node.js core but is backported by agentkeepalive. ```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... } }) ``` -------------------------------- ### Monitor Agent Status with getCurrentStatus() in Node.js Source: https://context7.com/node-modules/agentkeepalive/llms.txt The `getCurrentStatus()` method provides a snapshot of the agent's internal state, including socket counts and request metrics. This is useful for debugging and monitoring connection pooling behavior. It requires the `agentkeepalive` and `http` modules. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const agent = new HttpAgent({ maxSockets: 10, maxFreeSockets: 5, freeSocketTimeout: 15000, }); // Make multiple concurrent requests const makeRequest = (id) => { return new Promise((resolve, reject) => { const req = http.get({ host: 'httpbin.org', path: '/get', agent: agent, }, res => { let body = ''; res.on('data', chunk => { body += chunk; }); res.on('end', () => resolve({ id, status: res.statusCode })); }); req.on('error', reject); }); }; // Run concurrent requests and check status Promise.all([ makeRequest(1), makeRequest(2), makeRequest(3), ]).then(results => { console.log('Requests completed:', results); // Get detailed agent status const status = agent.getCurrentStatus(); console.log('Agent Status:', JSON.stringify(status, null, 2)); // Output example: // { // "createSocketCount": 3, // "createSocketErrorCount": 0, // "closeSocketCount": 0, // "errorSocketCount": 0, // "timeoutSocketCount": 0, // "requestCount": 3, // "freeSockets": { "httpbin.org:80:": 3 }, // "sockets": {}, // "requests": {} // } }); ``` -------------------------------- ### Handle ECONNRESET with req.reusedSocket in Node.js Source: https://context7.com/node-modules/agentkeepalive/llms.txt This snippet demonstrates how to use `req.reusedSocket` to detect if a request utilized a reused socket. This is crucial for implementing automatic retry logic when encountering 'ECONNRESET' errors, often caused by keep-alive race conditions. It requires the `agentkeepalive` and `http` modules. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const agent = new HttpAgent({ keepAlive: true, freeSocketTimeout: 30000, }); function makeRequestWithRetry(options, retries = 3) { return new Promise((resolve, reject) => { const doRequest = (attempt) => { const req = http.request({ ...options, agent }, res => { let body = ''; res.on('data', chunk => { body += chunk; }); res.on('end', () => resolve({ status: res.statusCode, body, attempt })); }); req.on('error', err => { // Check if error occurred on a reused socket if (req.reusedSocket && err.code === 'ECONNRESET' && attempt < retries) { console.log(`ECONNRESET on reused socket, retrying (attempt ${attempt + 1}/${retries})`); // Retry the request - the agent will create a new socket doRequest(attempt + 1); } else { reject(err); } }); req.end(); }; doRequest(1); }); } // Usage makeRequestWithRetry({ host: 'api.example.com', port: 80, path: '/data', method: 'GET', }) .then(result => console.log('Success:', result)) .catch(err => console.error('Failed after retries:', err.message)); ``` -------------------------------- ### Detect Status Changes with statusChanged Getter in Node.js Source: https://context7.com/node-modules/agentkeepalive/llms.txt The `statusChanged` getter property efficiently indicates if the agent's internal counters have been modified since the last check. This is useful for implementing status monitoring without needing to compare entire status objects repeatedly. It relies on the `agentkeepalive` and `http` modules. ```javascript const http = require('http'); const HttpAgent = require('agentkeepalive').HttpAgent; const agent = new HttpAgent({ maxSockets: 5, freeSocketTimeout: 10000, }); // Periodic status monitoring const monitorInterval = setInterval(() => { if (agent.statusChanged) { // Status has changed since last check console.log('[%s] Agent status changed:', new Date().toISOString()); console.log(JSON.stringify(agent.getCurrentStatus(), null, 2)); } }, 1000); // Make requests to trigger status changes const makeRequests = async () => { for (let i = 0; i < 5; i++) { const req = http.get({ host: 'httpbin.org', path: `/delay/1`, agent: agent, }, res => { res.on('data', () => {}); res.on('end', () => console.log(`Request ${i + 1} completed`)); }); req.on('error', e => console.error(`Request ${i + 1} error:`, e.message)); } }; makeRequests(); // Stop monitoring after 30 seconds setTimeout(() => { clearInterval(monitorInterval); console.log('Final status:', agent.getCurrentStatus()); }, 30000); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.