每個人,
我在 Node.js 中撰寫了一個 lambda,它獲取一個檔案夾并壓縮其內容。為此,我使用了 Archiver 庫:Archiver
以下是我創建檔案的代碼:
const zipFilePath = '/tmp/' 'filename' '.zip'
const output = fs.createWriteStream(zipFilePath);
const archive = archiver('zip', {
zlib: { level: 9 }
});
output.on('close', function () {
console.log(archive.pointer() ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function(err){
throw err;
});
await archive.pipe(output);
await archive.directory(destFolder, false);
await archive.finalize();
要撰寫檔案,我使用 lambdas 的 /tmp 檔案夾,這是唯一具有寫入權限的檔案夾。
流程如下:
- 我得到檔案夾的路徑
- 壓縮內容并將其保存在檔案夾 destFolder
然后將該檔案保存在 S3 存盤桶中:
const file = await fs.readFileSync(filePath)
const params = {
Bucket: bucketName,
Key: fileName,
Body: file
};
const res = await s3.upload(params).promise()
return res.Location
生成了zip檔案,問題是當我下載它時,它已損壞。我嘗試使用在線 zip 檔案分析器(this)對其進行分析,分析結果如下:
Type = zip
ERRORS:
Unexpected end of archive
WARNINGS:
There are data after the end of archive
Physical Size = 118916
Tail Size = 19
Characteristics = Local
分析器顯示檔案都存在于 .zip 中(我可以看到它們的名稱)。
最奇怪的是,如果不是 .zip 檔案(再次使用相同的庫)我在 .tar 中創建它
const archive = archiver('tar', {
zlib: { level: 9 }
});
該檔案已正確生成,我可以將其提取為存檔。基本上,好像 .zip 格式本身就有問題。
有沒有人經歷過類似的情節?你能幫我找到解決辦法嗎?我需要以 .zip 格式創建檔案。謝謝你。
uj5u.com熱心網友回復:
問題是您無法正確壓縮檔案,這可能由許多問題引起,包括:
- 您不是在等待檔案被處理,您需要使用
.close()事件來執行此操作。 - 您沒有將檔案或目錄的正確路徑發送到壓縮檔案,通常您與專案根目錄上的 lambda 檔案一起上傳的檔案保留在
/var/task/Lambda 目錄系統上,因此要發送正確的檔案使用__dirname '/file.name' - 您沒有正確附加檔案,如果您正確發送檔案,請檢查
.file()和方法.append()
如果您有以下 Lambda 結構:
~/my-function
├── index.js
└── node_modules
├── package.json
├── package-lock.json
├── test.txt //file to be sent zipped on s3
以下示例適用于您:
const archiver = require('archiver')
const fs = require('fs')
const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const sendToS3 = async (filePath) => {
const bucketName = "bucket_name";
const fileName = "zipped.zip"
const file = await fs.readFileSync(filePath)
const params = {
Bucket: bucketName,
Key: fileName,
Body: file
};
const res = await s3.upload(params).promise()
return res.Location
}
exports.handler = async event => {
return new Promise((resolve, reject) => {
const zippedPathName = '/tmp/example.zip';
const output = fs.createWriteStream(zippedPathName);
const fileToBeZipped = __dirname '/test.txt';
const zip = archiver('zip')
zip
.append(fs.createReadStream(fileToBeZipped), { name: 'test.txt' })
.pipe(output)
zip.finalize()
output.on('close', (result => {
sendToS3(zippedPathName).then(result => {
resolve(result)
})
}))
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428680.html
標籤:节点.js 亚马逊网络服务 亚马逊-s3 aws-lambda 压缩文件
