Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

response.body.getReader is not a function

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();
like image 459
user8565662 Avatar asked Jun 07 '26 11:06

user8565662


1 Answers

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 !

like image 71
Valentin Avatar answered Jun 09 '26 00:06

Valentin