HTTP/HTTPS Agent Resolver

1.0.2 · maintenance · verified Wed Apr 22

`http-https-agent` is a small, focused utility package designed to simplify the selection of appropriate Node.js HTTP or HTTPS agents based on a given URL's protocol. It provides a single factory function that, when invoked with agent options (like `keepAlive`), returns another function capable of dynamically providing either an `http.Agent` or `https.Agent` instance. The package is currently at version 1.0.2. Due to its minimal scope and lack of recent updates (last published several years ago), it appears to be in a maintenance-only state. Its primary differentiator is consolidating agent management for dual-protocol scenarios, avoiding manual `if/else` checks for agent instantiation. It internally relies on `lodash.startswith` for protocol detection.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize the agent factory with options and then use the returned function to dynamically obtain an HTTP or HTTPS agent based on the provided URL, confirming their types.

import httpHttpsAgent from 'http-https-agent';
import https from 'https';
import http from 'http';

// Create an agent factory with global options, e.g., keepAlive
const getAgent = httpHttpsAgent({
  keepAlive: true,
  maxSockets: 10,
  timeout: 60000 // 60 seconds
});

// Get an HTTPS agent for an HTTPS URL
const httpsUrl = 'https://jsonplaceholder.typicode.com/posts/1';
const myHttpsAgent = getAgent(httpsUrl);
console.log(`HTTPS Agent created for ${httpsUrl}:`, myHttpsAgent instanceof https.Agent); // Should be true

// Get an HTTP agent for an HTTP URL
const httpUrl = 'http://example.com'; // Note: Many public APIs enforce HTTPS
const myHttpAgent = getAgent(httpUrl);
console.log(`HTTP Agent created for ${httpUrl}:`, myHttpAgent instanceof http.Agent); // Should be true

// Example of using the agent in a request (simplified for demonstration)
https.get({ hostname: 'jsonplaceholder.typicode.com', path: '/posts/1', agent: myHttpsAgent }, (res) => {
  console.log('HTTPS Request status:', res.statusCode);
  res.resume();
}).on('error', (e) => {
  console.error('HTTPS Request error:', e.message);
});

view raw JSON →