timed-out HTTP/HTTPS Request Timeout

7.0.0 · active · verified Tue Apr 21

The `timed-out` package provides a simple and effective mechanism for adding timeout functionality to Node.js `http.ClientRequest` objects, preventing requests from hanging indefinitely. It automatically emits an `Error` object with specific `code` properties (`ETIMEDOUT` or `ESOCKETTIMEDOUT`) when a request exceeds its defined time limit. The current stable version is `7.0.0`. The project maintains a steady release cadence, typically introducing new major versions to align with Node.js LTS releases and introduce breaking changes like pure ESM adoption. Its key differentiator lies in its focused approach: it specifically extends the native `ClientRequest` object, offering granular control over connection and socket activity timeouts, rather than being part of a larger HTTP client library. This makes it a lightweight solution for augmenting existing `http` and `https` module usage without introducing a full-fledged client.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply both simple and granular connect/socket timeouts to Node.js `http.ClientRequest` instances, including proper error and timeout event handling.

import http from 'node:http';
import timedOut from 'timed-out';

// Example 1: Basic timeout for a GET request
const request1 = http.get('http://www.google.com', (res) => {
  console.log('Request 1 response status:', res.statusCode);
  res.resume(); // Consume response data to prevent memory leaks
});
timedOut(request1, 2000); // Sets a 2-second timeout

request1.on('timeout', () => {
  request1.destroy(new Error('Request 1 timed out after 2 seconds'));
  console.error('Request 1 timed out!');
});

request1.on('error', (err) => {
  if (err.code === 'ETIMEDOUT' || err.code === 'ESOCKETTIMEDOUT') {
    console.error('Request 1 failed due to timeout:', err.message);
  } else {
    console.error('Request 1 encountered an error:', err.message);
  }
});

// Example 2: Granular connect and socket timeouts for a different request
const request2 = http.get('http://www.example.com', (res) => {
  console.log('Request 2 response status:', res.statusCode);
  res.resume();
});
timedOut(request2, { connect: 1000, socket: 3000 }); // Connect timeout 1s, socket activity timeout 3s

request2.on('timeout', () => {
  request2.destroy(new Error('Request 2 timed out'));
  console.error('Request 2 timed out!');
});

request2.on('error', (err) => {
  if (err.code === 'ETIMEDOUT' || err.code === 'ESOCKETTIMEDOUT') {
    console.error('Request 2 failed due to timeout:', err.message);
  } else {
    console.error('Request 2 encountered an error:', err.message);
  }
});

// In a real application, ensure all requests are explicitly handled or destroyed
// to prevent lingering connections or memory leaks. For testing timeouts, 
// you might need to use a slow or non-existent endpoint.

view raw JSON →