【问题标题】:Serverless lambda trigger read json file无服务器 lambda 触发器读取 json 文件
【发布时间】:2019-09-06 00:35:29
【问题描述】:

我有一个 lambda(节点),当一个新的 JSON 文件添加到我们的 S3 存储桶时,它会触发。这是我的 lambda 代码

module.exports.bookInfo = (event, context) => {
  console.log('Events ', JSON.stringify(event));
   event.Records.forEach((record) =>  {
      const filename = record.s3.object.key;
      const bucketname = record.s3.bucket.name;
      let logMsg = [];
      const s3File = `BucketName: [${bucketname}] FileName: [${filename}]`;
      console.log(s3File)
      logMsg.push(`Lambda execution started for ${s3File}, Trying to download file from S3`);
      try {
        s3.getObject({
          Bucket: bucketname,
          Key: filename
        }, function(err, data) {
          logMsg.push('Data is ', JSON.stringify(data.Body))
          if (err) {
                logMsg.push('Generate Error :', err);
                console.log(logMsg)
                return null;
              }          
          logMsg.push(`File downloaded successfully. Processing started for ${s3File}`);  
          logMsg.push('Data is ', JSON.stringify(data.Body))
          });
          } catch (e) {console.log(e)}
          });
          }

当我运行它时,我没有得到文件内容,我怀疑 lambda 在文件读取操作完成之前完成了执行。我尝试了异步等待但没有成功。我在这里缺少什么?我能够读取 1 kb 的小文件,但是当我的文件增长到 100 MB 时,就会出现问题。

提前致谢

【问题讨论】:

  • 我怀疑 s3.getObject 是一个异步调用,所以你需要显式等待调用

标签: node.js aws-lambda serverless-framework


【解决方案1】:

我能够通过 async/await 做到这一点。这是我的代码

module.exports.bookInfo = (event, context) => {
  
   event.Records.forEach(async(record) =>  {
      const filename = record.s3.object.key;
      const bucketname = record.s3.bucket.name;
      const s3File = `BucketName: [${bucketname}] FileName: [${filename}]`;
      logMsg.push(`Lambda execution started for ${s3File}, Trying to download file from S3`);
      let response = await s3.getObject({
        Bucket: bucketname,
        Key: filename
      }).promise();
      })
      }

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多