UNPKG

just-zip

Version:

Just Zip both files and directories with ease

70 lines (64 loc) 1.94 kB
(function() { var archiver, fs, path; fs = require('fs'); archiver = require('archiver'); path = require('path'); module.exports = function(filePaths, zipFilePath, callback) { var add, archive, defaultZipFileName; if (callback == null) { callback = function() {}; } if (typeof filePaths === 'string') { filePaths = [filePaths]; } defaultZipFileName = path.basename(filePaths[0], path.extname(filePaths[0])) + '.zip'; if (typeof zipFilePath === 'function') { callback = zipFilePath; zipFilePath = defaultZipFileName; } archive = archiver('zip'); archive.on('error', callback); add = function() { var filePath; filePath = filePaths.shift(); if (filePath) { return fs.stat(filePath, function(err, stats) { if (err) { archive.abort(); return callback(err); } if (stats.isDirectory()) { archive.directory(filePath); } else { archive.file(filePath, { name: path.basename(filePath) }); } return add(); }); } else { return fs.stat(zipFilePath, function(err, stats) { var writeSteam; if (err && err.errno !== 34) { archive.abort(); return callback(err); } if (!err && stats.isDirectory()) { zipFilePath = path.join(zipFilePath, defaultZipFileName); } writeSteam = fs.createWriteStream(zipFilePath); writeSteam.on('error', function(err) { archive.abort(); return callback(err); }); writeSteam.on('close', function() { return callback(null, path.resolve(zipFilePath)); }); archive.pipe(writeSteam); return archive.finalize(); }); } }; return add(); }; }).call(this);