如何从S3存储最近上传的压缩文件时,我们使用节点JS触发拉姆达

问题描述 投票:-1回答:1

我上传的zip文件到S3存储,一旦我上传的zip文件,我的拉姆达功能将得到触发。

里面的lambda函数块,我需要根据从S3桶或对象的创建日期从LAMBDA记录事件的zip文件的最后修改日期为GET最近上传的zip文件名

但是它可能是,但我需要从S3存储最近上传的zip文件名。**

这是我的代码

s3.listObjects(params, function (err, data) {
    if (err)
        console.log(err, err.stack); // an error occurred


    var lastZipfile = null;
    var lastModified = null;
    data.Contents.forEach(function (c) {
        if (c.Key.endsWith('tar.gz')) {
            if (lastModified === null) {
                lastZipfile = c.Key;
                lastModified = c.LastModified;
            } else {
                // Compare the last modified dates
                if (lastModified <= c.LastModified) {
                    // Track the new latest file
                    lastZipfile = c.Key;
                    lastModified = c.LastModified;
                    //extractData(lastZipfile);
                }
            }
        }

    });
});
node.js amazon-s3 aws-lambda
1个回答
1
投票

我会告诉你两个选项来解决这个问题。

1º选项(自动): 我看到的最好的办法是有一个lambda函数准备每次文件被放置在水桶S3时自动运行。当lambda函数被调用,从创建的文件信息的事件将被发送到lambda函数。

下面是如何触发一个例子:

enter image description here

下一个:

enter image description here

下面是一个例子来做到这一点:

exports.handler = (event, context, callback) => {

  var lastCreatedFile = event.Records[0].s3.object.key;
  //extractData(lastCreatedFile);

};

2º选项(手动地): 但是,只要你想获得新文件信息,您可以拨打您手动lambda函数。与您的代码,你总是会得到/修改的最后文件中创建。

我已经调整您所提交做到这一点您的lambda表达式:

s3.listObjects(params, function (err, data) {
if (err)
    console.log(err, err.stack); // an error occurred

var sortArray;

data.Contents.sort(function(a,b) {
    return (b.LastModified > a.LastModified) ? 1 :
    ((a.LastModified > b.LastModified) ? -1 : 0);
});

for(var file of data.Contents){
    if (file.Key.endsWith('tar.gz')) {
        //extractData(file.Key);
        break;
    }
}

但是,我们可以有这样的问题,如果没有创建新的文件,它会发生提取相同的文件超过一次。我建议以后,使用该文件删除或另谋出路,以确定该文件已被使用。

我希望它帮你!

© www.soinside.com 2019 - 2024. All rights reserved.