node-fetch-retry

2.0.1 · maintenance · verified Sun Apr 19

node-fetch-retry is a lightweight wrapper library designed to enhance `node-fetch` with automatic retry capabilities. It enables developers to specify a fixed number of retry attempts for network requests, introduce a pause duration between retries, and execute a custom callback function before each attempt. The current stable version is 2.0.1. Its release cadence appears to be infrequent, with the last notable activity several years ago, suggesting it is in maintenance mode or effectively abandoned. This library differentiates itself by offering a straightforward, integrated retry mechanism directly within the `fetch` options, making it a simple choice for adding basic request resilience without complex configurations often found in more feature-rich alternatives. It's best suited for Node.js environments requiring basic retry logic for transient network failures.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates fetching a URL with a specified number of retries and a pause between attempts, including a callback to log each retry attempt.

import * as process from 'process';

const fetch = require('node-fetch-retry');

async function fetchDataWithRetry() {
  const targetUrl = 'https://httpstat.us/503?sleep=1000'; // Example URL that returns 503 after a delay
  const retries = 3;
  const pauseMs = 1000; // 1 second pause

  console.log(`Attempting to fetch from ${targetUrl} with ${retries} retries...`);

  try {
    let opts = {
      method: 'GET',
      retry: retries,
      pause: pauseMs,
      callback: (retryAttempt) => {
        console.log(`Retry attempt: ${retryAttempt}. Waiting ${pauseMs}ms before next attempt.`);
      },
      silent: false // Set to true to suppress pause messages
    };

    // Make the fetch request with retry options
    const res = await fetch(targetUrl, opts);

    if (res.ok) {
      const text = await res.text();
      console.log('Fetch successful after retries!');
      console.log('Response:', text.substring(0, 100) + '...');
    } else {
      console.error(`Fetch failed after all retries with status: ${res.status}`);
    }
  } catch (error) {
    console.error('An unhandled error occurred during fetch operation:', error.message);
  }
}

fetchDataWithRetry();

view raw JSON →