Last active
May 24, 2016 18:21
-
-
Save erkattak/143444e4af92e15138bfbefcd242e203 to your computer and use it in GitHub Desktop.
Node.js zip archiver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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