使用Node.js中的Promise从s3存储桶下载图像 [英] Download images from s3 bucket using Promise in node.js
本文介绍了使用Node.js中的Promise从s3存储桶下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用node.js中的Promises从本地系统的s3存储桶中下载一些图像文件.
I want to download some image files from s3 bucket on my local system using Promises in node.js.
var params = {
Bucket: bucket_name',
Key: 'key'
};
var fileStream = fs.createWriteStream('path/to/file.jpg');
我尝试了这个可行的方法
I tried this which is working
s3.getObject(params).createReadStream.pipe(fileStream);
但是我希望我的代码看起来像这样
But I want my code look like this
return s3.getObject(params).promise()
.then(function(data) {
//console.log(data.Body);
// No idea about this section
})
.catch(function(err) {
throw err;
});
我必须使用Promise来确保应该下载所有图像.
I have to use Promise to ensure all images should be downloaded.
推荐答案
一种可能的解决方案是使用bluebird
并创建一个在流的末尾返回promise的函数:
One possible solution is to use bluebird
and create a function that returns a promise on the end of the stream:
const B = require('bluebird');
function downloadFromS3 (object) {
var p = B.Promise.defer();
var stream = s3.getObject(params).createReadStream()
stream.pipe(fileStream);
stream.on('error', (e) => p.reject(e))
stream.on('end', () => p.resolve())
return p.promise;
}
downloadFromS3(params)
.then(() => console.log('finished'))
.catch(() => console.log('failed'))
不确定此代码是否特别有用,但可能会为您提供指导.
Not sure if this code specifically would work, but it may give you a direction to look into.
这篇关于使用Node.js中的Promise从s3存储桶下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文