Node AbortController Polyfill

3.1.1 · maintenance · verified Tue Apr 21

node-abort-controller provides a minimal polyfill for the AbortController and AbortSignal Web APIs, specifically designed for Node.js environments running versions 14.6.x and below. It leverages Node.js's EventEmitter for its implementation. This package is explicitly *not* needed for Node.js versions 14.7.0 and above, as `AbortController` and `AbortSignal` are built-in globals in modern Node.js environments, becoming stable in v15.4.0. The library's current stable version is 3.1.1, and its release cadence is tied to the evolving Node.js core, with updates typically occurring when there are breaking changes or new Node.js versions make the polyfill redundant. Its key differentiator is its lightweight, Node.js-specific approach, aiming to avoid shipping unnecessary polyfills to environments that don't require them, making it ideal for library authors targeting mixed Node.js and modern browser environments where `node-fetch` is also used.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use AbortController with `node-fetch` to implement a timeout for an HTTP request, showing how to create a controller, pass its signal, and handle the abort event.

import fetch from 'node-fetch';
import { AbortController } from 'node-abort-controller';

const main = async () => {
  const controller = new AbortController();
  const signal = controller.signal;

  // Abort fetch after 500ms. Effectively a timeout
  const timeoutId = setTimeout(() => {
    console.log('Request timed out, aborting...');
    controller.abort();
  }, 500);

  try {
    console.log('Fetching from Google...');
    const response = await fetch('https://www.google.com', { signal });
    clearTimeout(timeoutId);
    if (response.ok) {
      console.log(`Successfully fetched Google (Status: ${response.status})`);
      // const text = await response.text();
      // console.log(text.substring(0, 100) + '...');
    } else {
      console.error(`Failed to fetch Google (Status: ${response.status})`);
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      console.warn('Fetch request was aborted.');
    } else {
      console.error('Fetch error:', error.message);
    }
  }
};

main();

view raw JSON →