Skip to content

Instantly share code, notes, and snippets.

@erkattak
Last active May 24, 2016 18:21
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 erkattak/143444e4af92e15138bfbefcd242e203 to your computer and use it in GitHub Desktop.
Save erkattak/143444e4af92e15138bfbefcd242e203 to your computer and use it in GitHub Desktop.
Node.js zip archiver
#!/usr/bin/env node
'use strict';
const _ = require('lodash');
const filepath = require('filepath');
const Promise = require('bluebird');
const Archiver = require('archiver');
const output = filepath.create(process.env.OUTPUT).newWriteStream();
const archive = Archiver('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);
const directory = filepath.create(process.env.INPUT);
function relativeBasename(file) {
return _.difference(file.path.split('/'), directory.path.split('/')).join('/');
}
function appendFiles(archive, files) {
const promises = [];
for(let file of files) {
if (file.isDirectory()) {
promises.push(appendFiles(archive, file.list()));
} else {
promises.push(Promise.resolve(archive.append(file.newReadStream(), { name: relativeBasename(file) })));
}
}
return Promise.all(promises);
}
Promise.resolve(directory.list())
.then(files => {
return appendFiles(archive, files);
})
.then(() => {
archive.finalize();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment