问题
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();
回答1:
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 !
来源:https://stackoverflow.com/questions/57664058/response-body-getreader-is-not-a-function