Skip to content

Instantly share code, notes, and snippets.

@TifPun
Last active October 7, 2016 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TifPun/ed35cdf64bd61b88ffb8df31bf167b7d to your computer and use it in GitHub Desktop.
Save TifPun/ed35cdf64bd61b88ffb8df31bf167b7d to your computer and use it in GitHub Desktop.
zip files and folders using node-archiver.js
/*
Pre-requisite: npm --save archiver
Suppose the folder `/Users/x/baseFolder` has the following structure:
/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
The code below creates a result.zip file using some of the contents from the folder. The contents in the output file preserves the same folder structure as the source folder, i.e. :
/Users/x/baseFolder/result.zip
| __ dir1
| __ file1.txt
| __ dir2
| __ file3.txt
| __ file4.txt
| __ dir3
| __ file6.txt
| __ file7.txt
| __ file8.txt
| __ file9.txt
*/
var fs = require('fs');
var path = require('path');
var archiver = require("archiver");
function zipFolder(baseFolder) {
var archive = archiver('zip'); // a new archive instance is needed for each run of the archive
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;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment