HTTP connection pool — reuse TCP connections for performance.
1const http = require("http");2const https = require("https");34const agent = new http.Agent({5 keepAlive: true,6 maxSockets: 50,7 maxFreeSockets: 10,8 timeout: 60000,9});1011const httpsAgent = new https.Agent({12 keepAlive: true,13 maxSockets: 50,14 rejectUnauthorized: true,15});1617async function request(url, options = {}) {18 return new Promise((resolve, reject) => {19 const urlObj = new URL(url);20 const mod = urlObj.protocol === "https:" ? https : http;2122 const req = mod.request(url, {23 ...options,24 agent: urlObj.protocol === "https:" ? httpsAgent : agent,25 }, (res) => {26 let data = "";27 res.on("data", chunk => data += chunk);28 res.on("end", () => resolve({ status: res.statusCode, data }));29 });3031 req.on("error", reject);32 req.end();33 });34}
Key points: