0

从 aws cloudwatch 登录

20:42:36
START RequestId: 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b Version: $LATEST
20:42:39
END RequestId: 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b
20:42:39
REPORT RequestId: 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b Duration: 3003.18 ms Billed Duration: 3000 ms Memory Size: 128 MB Max Memory Used: 128 MB Init Duration: 703.55 ms
REPORT RequestId: 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b  Duration: 3003.18 ms    Billed Duration: 3000 ms    Memory Size: 128 MB Max Memory Used: 128 MB Init Duration: 703.55 ms    
20:42:39
2020-01-06T15:12:39.657Z 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b Task timed out after 3.00 seconds
2020-01-06T15:12:39.657Z 3b39ddb6-f2f5-4e11-a3d6-59f47f16240b Task timed out after 3.00 seconds

Node.js AWS Lambda 代码

const aws = require('aws-sdk');
const Jimp = require("jimp");
const uuid = require("uuid/v4");
const s3 = new aws.S3();
//lambda trigger handler for triggering event after object being uploaded into bucket
exports.handler = async (event, context) => {
  const key = event.Records[0].s3.object.key; // Uploaded object key
  const sanitizedKey = key.replace(/\+/g, ' ');
  const keyWithoutExtension = sanitizedKey.replace(/.[^.]+$/, '');
  const objectKey = keyWithoutExtension+'_mb.';

//read object using jimp to resize it accordingly
  const image = await Jimp.read(prefix+key)
                      .then((image) => {
                        console.log( "Before resizing" , image)
                        return image
                          .resize(256, 256) // resize
                          .quality(90) // set JPEG quality
                      })
                     .then((image) => {
                      return uploadToS3(image, objectKey+image.getExtension(), image.getExtension());
                      })
                      .catch(err => {
                        throw err;
                      })
                      .finally(() => {
                        console.info("Function ran successfully")
                      })
  console.log(image);
  return image
}
//upload file to s3 after resizing
async function uploadToS3(data, key, ContentType) {
  console.log("Inside uploadToS3: ", data, key, ContentType)
  const resp = await s3
    .putObject({
      Bucket: Bucket,
      Key: key,
      Body: data,
      ContentType: ContentType
    })}
  console.log("Response from S3: ", resp);
  return resp
}
4

1 回答 1

0

除了方法的微小变化外,一切看起来都很好uploadToS3。默认情况下使用回调模式,除非你.promise()最后这样做。查看更新的方法

//upload file to s3 after resizing
async function uploadToS3(data, key, ContentType) {
  console.log("Inside uploadToS3: ", data, key, ContentType)
  const resp = await s3
    .putObject({
      Bucket: Bucket,
      Key: key,
      Body: data,
      ContentType: ContentType
    }).promise();
  console.log("Response from S3: ", resp);
  return resp
}

除了默认的 3 秒之外,还值得将您的 lambda 超时增加到其他值,以排除它在操作完成之前超时。

希望这可以帮助

于 2020-01-07T09:04:37.573 回答