HTTP
http.Agent
Manage native HTTP sockets with explicit pool configuration and lifetime. Local Node 22.16.0; production target compatibility pending. See https://nodejs.org/download/release/v22.16.0/docs/api/http.html.
Formal Syntax & Structure
nodejs syntaxnodejs
new http.Agent([options])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| options | object | Socket pool options. |
Return Value
http.Agent
Result or receiver of the documented operation; see the linked versioned API contract.
Working Example
Example Snippetnodejs
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});import { Agent, get } from 'node:http';function getText(url,agent){return new Promise((resolve,reject)=>{ const req=get(url,{agent,signal:AbortSignal.timeout(2000)},res=>{ let text='';res.setEncoding('utf8');res.on('data',c=>{text+=c;});res.on('end',()=>resolve({text,reused:req.reusedSocket}));res.on('error',reject); });req.on('error',reject);});}await withServer((q,r)=>r.end('stock'),async base=>{const agent=new Agent({keepAlive:true,maxSockets:1});try{console.log((await getText(base,agent)).text);}finally{agent.destroy();}});