我有以下情况:
getStream 从请求返回流
我想将流传递给downloadImage,但是我遇到了一个问题:履行“downloadImage”中的 promise ,它不会产生我预期的流。
class ImageDownloader {
private async getStream(imageUrl){
const result = request(imageUrl);
// result.pipe(fs.createWriteStream('./image.jpg')); //it is a stream and it works to write it in a file
return result;
}
public async downloadImage(imageUrl) {
const imageStream = await getStream(imageUrl);
// imageStream.pipe(fs.createWriteStream('./image.jpg'));
//I receive the following error: "imageStream.pipe is not a function"
}
}
如何使用 Promises 异步传递流?我做错了什么?
注意:我简化了此示例的方法
提前谢谢
最佳答案
当您不在方法内使用 await
时,尚不清楚为什么将 getStream
标记为 async
。调用类方法时还需要使用 this
(例如 this.getStream(...)
)。
看起来您正在尝试编写一个下载图像(使用流 API)并返回 promise 的方法,这就是我的做法:
class ImageDownloader {
private getStream(imageUrl) {
return request.get(imageUrl);
}
public downloadImage(imageUrl) {
return new Promise((resolve, reject) => {
this.getStream(imageUrl)
.pipe(fs.createWriteStream('./image.jpg'))
.on('finish', resolve)
.on('error', reject);
});
}
}
然后你就可以使用它了:
const downloader = new ImageDownloader();
await downloader.downloadImage('http://host.com/image.jpg');
此答案假设您正在使用 request
模块。
关于javascript - 我无法在 Node 中使用 Promise 读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60198146/