[英]Nothing inside the S3 API's getObject callback is running in Lambda function
我遇到了无法从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!')
})
}
如果您尝试使用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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.