8

I'm making a call to a web api using fetch. I want to read the response as a stream however when I call getReader() on response.body I get the error: "TypeError: response.body.getReader is not a function".

  const fetch = require("node-fetch");
  let response = await fetch(url);
  let reader = response.body.getReader();
user8565662
  • 127
  • 1
  • 1
  • 6

1 Answers1

21

There is a difference between the javascript implementation of fetch and the one of node node-fetch.

You can try the following:

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

fetch(url)
    .then(response => response.body)
    .then(res => res.on('readable', () => {
    let chunk;
    while (null !== (chunk = res.read())) {
        console.log(chunk.toString());
    }
}))
.catch(err => console.log(err));

The body returns a Node native readable stream, which you can read using the conveniently named read() method.

You can find more about the differences under here. More specifically:

For convenience, res.body is a Node.js Readable stream, so decoding can be handled independently.

Hope it helps !

Valentin
  • 400
  • 1
  • 4
  • 14