Response Iterator

1.0.10 · active · verified Tue Apr 21

response-iterator is a utility library designed to normalize various HTTP response bodies into a consistent asynchronous iterator interface, compatible across both browser and Node.js environments. It currently stands at stable version 1.0.10 and is regularly maintained. The library abstracts away the differences in how `Response` objects (or similar constructs) are handled by different HTTP clients such as standard `fetch`, `node-fetch`, `cross-fetch`, `axios`, `got`, and `undici`. Its key differentiator is providing a simple `for await...of` loop mechanism to consume streamed data chunks, making it easier to process large responses efficiently without loading the entire body into memory, irrespective of the underlying fetch implementation. It significantly simplifies working with streaming data by adhering to the `Symbol.asyncIterator` protocol.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates fetching a JSON file and consuming its content as an async iterator.

import responseIterator from 'response-iterator';

// A polyfill like 'isomorphic-fetch' or 'node-fetch' might be needed for Node.js environments
// if a global `fetch` is not available. For browser, `fetch` is native.

async function fetchData() {
  try {
    const res = await fetch('https://raw.githubusercontent.com/kmalakoff/response-iterator/master/package.json');
    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`);
    }

    let data = '';
    for await (const chunk of responseIterator(res)) {
      data += chunk;
    }
    console.log('Package name:', JSON.parse(data).name); // Expected: "response-iterator"
  } catch (error) {
    console.error('Failed to fetch or process data:', error);
  }
}

fetchData();

view raw JSON →