【发布时间】:2019-03-01 07:24:17
【问题描述】:
我一直在尝试(但失败)使用 Node 版本 8.10 中的 s3.getObject 从 S3 存储桶加载文件。
我发现了一篇很棒的帖子,其中回复了几乎可以正常工作的 here,但语法在 8.10 中不太适用,无论我如何重新安排代码,我都无法使其正常工作。
var AWS = require('aws-sdk')
var s3 = new AWS.S3();
var fileData = null;
exports.handler = (event, context, callback) => {
console.log('I am in the main procedure');
var params = {
Bucket: "change_for_your_bucket",
Key: "change_to_your_json_file"
};
fetchDataFromS3(params);
console.log('I am in the main procedure, the function above should be waiting but it is not');
waitForFileLoadBeforeDoingSomething(event, context, callback);
const s = JSON.stringify(fileData.Body.toString('utf-8'));
console.log(`this is the file: ${s}`);
console.log('I have the file!(dg.2)');
};
function fetchDataFromS3(params)
{
console.log('-------------- fetchDataFromS3:Start -------------------------');
// gets the object from s3 => promise
const uploadPromise = s3.getObject(params).promise();
// returns the body of the s3 object
uploadPromise
.then(function(data) {
console.log("successfully downloaded data");
fileData = data.Body.toString();
})
.catch(function download(err) {console.log(err,err.stack); throw err;});
console.log('-------------- fetchDataFromS3:Done -------------------------');
}
function waitForFileLoadBeforeDoingSomething(event, context, callback){
if(!fileData){
console.log('No file available to me as yet, lets sleep for a bit');
setTimeout(function(){
waitForFileLoadBeforeDoingSomething(event, context, callback);
}, 300);
}
}
输出如下。
Function Logs:
START RequestId: cb16f155-c0d7-11e8-ad01-f5991c5adaaf Version: $LATEST
2018-09-25T15:29:29.759Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf I am in the main procedure
2018-09-25T15:29:29.759Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf -------------- fetchDataFromS3:Start -------------------------
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf -------------- fetchDataFromS3:Done -------------------------
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf I am in the main procedure, the function above should be waiting but it is not
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf No file available to me as yet, lets sleep for a bit
2018-09-25T15:29:29.812Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf TypeError: Cannot read property 'Body' of null
at exports.handler (/var/task/dg3.js:17:39)
您可以看到我没有点击“成功下载数据”行,如果我犯了一个错误并且该函数仍在异步运行,或者如果我获得了 promise 的语法,我无法解决错了。
【问题讨论】:
标签: node.js amazon-s3 aws-lambda