@sstauross 的回答非常适合我。我添加了更多代码以允许将目录和文件的混合添加到 zip 过程中:
假设文件夹/Users/x/baseFolder
具有以下结构:
/Users/x/baseFolder
| __ dir1
| __ file1.txt
| __ file2.txt
| __ dir2
| __ file3.txt
| __ file4.txt
| __ dir3
| __ file5.txt
| __ file6.txt
| __ file7.txt
| __ file8.txt
| __ file9.txt
| __ file10.txt
我可以执行以下操作来创建/Users/x/baseFolder/result.zip
具有以下结构和内容的文件夹:
/Users/x/baseFolder/result.zip
| __ dir1
| __ file1.txt
| __ dir2
| __ file3.txt
| __ file4.txt
| __ dir3
| __ file6.txt
| __ file7.txt
| __ file8.txt
| __ file9.txt
function zipFolder(baseFolder) {
var archive = archiver('zip');
var fileNames = [
'dir1/file1.txt',
'dir3/file6.txt',
'dir3/file7.txt',
'file8.txt',
'file9.txt'
];
var folderNames = [
'dir2',
]
var output = fs.createWriteStream(path.join(baseFolder, "result.zip"));
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;
});
archive.pipe(output);
for (i = 0; i < fileNames.length; i++) {
var stream = fs.readFileSync(path.join(baseFolder, fileNames[i]));
archive.append(stream, { name: fileNames[i] });
}
for (i = 0; i < folderNames.length; i++) {
archive.directory(path.join(baseFolder, folderNames[i]), folderNames[i]);
}
archive.finalize(function (err, bytes) {
if (err) throw err;
});
}