Node.js HTTP Agents
The classic http client API exposes request objects and an Agent that manages connection reuse. Close resources you create when a bounded client task ends.
How it works
An Agent can reduce repeated connection setup, but its socket limits are not a full application queue or rate limiter. The fixture makes an actual local request with a dedicated keep-alive Agent, accumulates one tiny trusted body and destroys the Agent after use. For larger or unknown bodies, replace the collector with an explicitly bounded transfer. The response object is a readable stream, not an already-decoded text value.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as agent-lifecycle.mjs in a separate empty exercises folder and run node agent-lifecycle.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
import http from 'node:http';
import { once } from 'node:events';
const server = http.createServer((request, response) => response.end('kit'));
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const base = 'http://127.0.0.1:' + server.address().port;
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
try {
const body = await new Promise((resolve, reject) => {
const request = http.get(base, { agent }, (response) => {
let text = '';
response.setEncoding('utf8');
response.on('data', (chunk) => (text += chunk));
response.on('end', () => resolve(text));
response.on('error', reject);
});
request.on('error', reject);
});
console.log(body);
} finally {
agent.destroy();
server.closeAllConnections();
await new Promise((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
}
Expected result
kit
The request, response stream and Agent each have a distinct lifetime. Destroying an owned Agent is appropriate for this short fixture; a long-lived application usually shares a deliberately managed pool instead of recreating one for every request.
Use the Node.js API reference for the precise version contract.