【问题标题】:Extract zip file from S3 bucket with AWS Lambda function with Node.js and upload to another bucket使用带有 Node.js 的 AWS Lambda 函数从 S3 存储桶中提取 zip 文件并上传到另一个存储桶
【发布时间】:2017-04-29 14:03:39
【问题描述】:

我正在和AWS Lambda 一起玩Node.js。我创建了一个 lambda 函数并使用S3 event 对其进行配置。 我想提取在 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);
        }
    });
};

【问题讨论】:

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


    【解决方案1】:

    您可以使用 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);
                    });
                }
            });
        }
    });
    

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

    【讨论】:

    • gunzip 上出现错误Error: incorrect header check
    • 数据未压缩时抛出此错误。
    • 我该如何解决这个错误?你能更新你的答案吗?
    • 我也遇到了同样的问题。从常见问题解答中我了解到 zlib 无法处理“.zip”文件,它应该是“gzip”或“Deflate 压缩流”。关于如何使用 zlib 处理 .zip 扩展名的任何想法?
    • 正确,zlib 不处理 .zip 文件。此处的文档:nodejs.org/api/zlib.html
    猜你喜欢
    • 2020-09-15
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多