我正在使用 AWS Lambda
和 Node.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/