使用 Fetch API 和 fs.createWriteStream 对文件进行流式响应
Stream response to file using Fetch API and fs.createWriteStream
我正在创建一个 Electron 应用程序,我想将图像流式传输到一个文件(所以基本上是下载它)。
我想使用原生的 Fetch API,因为请求模块会是一个很大的开销。
但是响应上没有管道方法,所以我不能做类似的事情
fetch('https://imageurl.jpg')
.then(response => response.pipe(fs.createWriteStream('image.jpg')));
那么我如何结合fetch
和fs.createWriteStream
?
Fetch 并不能开箱即用地使用 nodejs 流,因为浏览器中的流 API 不同于 nodejs 提供的流,即您不能将浏览器流通过管道传输到 nodejs 流反之亦然。
electron-fetch module seems to solve that for you. Or you can look at this answer: 无需 nodeIntegration 即可下载文件。
还有 needle,一个更小的替代大容量请求的方法,它当然支持 Streams。
我成功了。我制作了一个将响应转换为可读流的函数。
const responseToReadable = response => {
const reader = response.body.getReader();
const rs = new Readable();
rs._read = async () => {
const result = await reader.read();
if(!result.done){
rs.push(Buffer.from(result.value));
}else{
rs.push(null);
return;
}
};
return rs;
};
有了它,我可以做到
fetch('https://imageurl.jpg')
.then(response => responseToReadable(response).pipe(fs.createWriteStream('image.jpg')));
我正在创建一个 Electron 应用程序,我想将图像流式传输到一个文件(所以基本上是下载它)。
我想使用原生的 Fetch API,因为请求模块会是一个很大的开销。
但是响应上没有管道方法,所以我不能做类似的事情
fetch('https://imageurl.jpg')
.then(response => response.pipe(fs.createWriteStream('image.jpg')));
那么我如何结合fetch
和fs.createWriteStream
?
Fetch 并不能开箱即用地使用 nodejs 流,因为浏览器中的流 API 不同于 nodejs 提供的流,即您不能将浏览器流通过管道传输到 nodejs 流反之亦然。
electron-fetch module seems to solve that for you. Or you can look at this answer:
还有 needle,一个更小的替代大容量请求的方法,它当然支持 Streams。
我成功了。我制作了一个将响应转换为可读流的函数。
const responseToReadable = response => {
const reader = response.body.getReader();
const rs = new Readable();
rs._read = async () => {
const result = await reader.read();
if(!result.done){
rs.push(Buffer.from(result.value));
}else{
rs.push(null);
return;
}
};
return rs;
};
有了它,我可以做到
fetch('https://imageurl.jpg')
.then(response => responseToReadable(response).pipe(fs.createWriteStream('image.jpg')));