我遇到了一个问题,无法从 S3 读取文件...甚至无法进入 S3 回调。我为我的 lambda 使用 Node 8.10,并且我已经验证了一切都在运行,直到我尝试进入 getObject 内部 - 下面的 console.log
甚至都不会运行。这里有什么东西看起来不对劲吗?我已授予 lambda 和 S3 的完全访问权限,因此我认为这不是问题所在。
const AWS = require('aws-sdk')
exports.handler = async (event, context, callback) => {
const s3options = {
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET,
apiVersion: '2006-03-01',
}
const params = {
Bucket: event.Records[0].s3.bucket.name,
Key: event.Records[0].s3.object.key,
}
const s3 = new AWS.S3(s3options)
s3.getObject(params, (err, data) => {
// callback(null, data.Body.toString('utf-8'))
console.log('I am here!')
})
}
最佳答案
如果您尝试使用 Node v8.x 的async/await功能,那么您必须将代码包装到try/catch中 block 并使用 promise (我的意思是没有必要包装您的函数代码,但您仍然必须在应用程序内实现 try/catch block )。
注意:AWS-SDK 已 promise ,意味着您不必 promise AWS-SDK 方法或使用回调。只需简单地将 .promise() 附加到您的方法作为尾部,并将 await 关键字作为前缀添加到您尝试调用的方法。
示例:
之前:
s3.getObject(params, (err, data) => {
// callback(null, data.Body.toString('utf-8'))
之后:
try
{
const s3Response = await s3.getObject(params).promise();
// if succeed
// handle response here
}
catch (ex)
{
// if failed
// handle response here (obv: ex object)
// you can simply use logging
console.error(ex);
}
那么你的代码必须如下所示:
// it's really cool to use ES6 syntax to import modules: import * as AWS from 'aws-sdk';
// btw, you don't have to import AWS-SDK inside the handler file
// const AWS = require('aws-sdk')
exports.handler = async (event) => {
const s3options =
{
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET,
apiVersion: '2006-03-01',
// do not forget include a region (e.g. { region: 'us-west-1' })
}
const params =
{
Bucket: event.Records[0].s3.bucket.name,
Key: event.Records[0].s3.object.key,
}
const s3 = new AWS.S3(s3options)
try
{
const s3Response = await s3.getObject(params).promise();
// if succeed
// handle response here
}
catch (ex)
{
// if failed
// handle response here (obv: ex object)
// you can simply use logging
console.error(ex);
}
}
关于node.js - S3 API 的 getObject 回调内部没有任何内容在 Lambda 函数中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52825290/