node.js - 使用 AWS Lambda 函数和 Node.js 从 S3 存储桶中提取 zip 文件并上传到另一个存储桶

标签 node.js amazon-web-services amazon-s3 lambda aws-lambda

我正在使用 AWS LambdaNode.js。我创建了一个 lambda 函数并使用 S3 事件 配置它。 我想提取在 S3 上上传的 zip 文件并将提取的文件上传到同一存储桶上的另一个文件夹。

我从以下代码中获取存储桶和文件信息,但之后我不知道如何提取并上传到 s3。

任何建议或代码块都会对我有帮助。

'use strict';

console.log('Loading function to get all latest object from S3 service');

const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' });


exports.handler = (event, context, callback) => {
    console.log('Received event:', JSON.stringify(event, null, 2));

    // Get the object from the event and show its content type
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: bucket,
        Key: key,
    };
    s3.getObject(params, (err, data) => {
        if (err) {
            console.log(err);
            const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
            console.log(message);
            callback(message);
        } else {
            console.log('CONTENT TYPE:', data.ContentType);
            callback(null, data);
        }
    });
};

最佳答案

您可以使用 zlib 解压缩从 s3 获得的缓冲区。

s3.getObject(params, (err, data) => {
    if (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        callback(message);
    } else {
        zlib.gunzip(data.Body, function (err, result) {
            if (err) {
                console.log(err);
            } else {
                var extractedData = result;
                s3.putObject({
                Bucket: "bucketName",
                Key: "filename",
                Body: extractedData,
                ContentType: 'content-type'
                }, function (err) {
                     console.log('uploaded file: ' + err);
                });
            }
        });
    }
});

我想上面的功能会对你有所帮助。

关于node.js - 使用 AWS Lambda 函数和 Node.js 从 S3 存储桶中提取 zip 文件并上传到另一个存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139257/

相关文章:

c# - 使用 .NET SDK 发布到 Amazon Web Services Kinesis 时出错

amazon-web-services - 使用 CloudFront 时,S3 上的自定义重定向规则返回 403

hadoop - 如何在 S3 上指定 Hive EXTERNAL TABLE 数据的文件大小

amazon-web-services - AWS S3 存储桶访问 token

amazon-s3 - 如何在写入 Redshift DW 之前转换 S3 存储桶中的数据?

node.js - Azure - 每个 Web 应用程序进行多个部署?

javascript - NPM 包 excel-as-json 提前触发回调

node.js - VirtualHost 不重定向

javascript - 使用带有 Express 的 NodeJS 从 MongoDB 检索数据

python - 使用 python boto 删除 Amazon EC2 实例