const S3Unzip = require('s3-unzip');
exports.handler = function(event, context, callback) {
const bucketname = event.Records[0].s3.bucket.name;
const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
new S3Unzip({
bucket: bucketname,
file: filename ,
verbose: true,
}, function(err, success) {
if (err) {
callback(err);
} else {
callback(null);
}
});
}
这是我当前用来解压 s3 存储桶中的 zip 文件的 lambda 函数代码。 我的要求是在上传到s3存储桶之前重命名解压的文件,我应该如何修改上面的代码来实现这一点? `
我尝试使用其他软件包,例如 unzipper,它需要文件系统来解压缩,然后我将能够重命名每个文件的文件名。但我不想那样做。我正在寻找是否可以使用 s3-unzip 包本身。
s3-unzip 软件包不提供在解压缩过程中重命名文件的内置方法。
但是,可以通过使用 AWS Lambda 在
/tmp
目录中的临时存储(最多 512MB)进行存档:
将 zip 文件上传到 /tmp 文件夹
使用 s3-unzip 解压文件。
重命名 /tmp 目录中的文件。
将重命名的文件上传到最终的 S3 位置。
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const fs = require('fs');
const path = require('path');
const unzipper = require('unzipper');
exports.handler = async function(event, context, callback) {
const bucketname = event.Records[0].s3.bucket.name;
const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
// Upload the zip file to the /tmp directory
const zipFilePath = path.join('/tmp', filename);
const fileStream = fs.createWriteStream(zipFilePath);
const s3Stream = s3.getObject({Bucket: bucketname, Key: filename}).createReadStream();
s3Stream.pipe(fileStream).on('error', (err) => {
callback(err);
}).on('close', async () => {
// Unzip the file in the /tmp directory
const directory = await unzipper.Open.file(zipFilePath);
for (let file of directory.files) {
const content = await file.buffer();
const originalName = file.path;
const newName = originalName.replace('.txt', '_renamed.txt');
// Upload the renamed file to S3
const putParams = {
Bucket: bucketname,
Key: 'finalFolder/' + newName,
Body: content
};
await s3.putObject(putParams).promise();
}
callback(null);
});
};