我遇到了无法从S3读取文件的问题,甚至无法进入S3回调。我正在为lambda使用节点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!')
})
}
答案 0 :(得分:2)
如果您尝试使用Node v8.x的 async / await 功能,则必须将代码包装为 try / catch 阻止并使用Promise(我的意思是没有必要包装功能代码,但是您仍然必须在应用程序内部实现try / catch阻止)。
注意:AWS-SDK已经实现,这意味着您没有来实现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);
}
}