just-zip
Version:
Just Zip both files and directories with ease
59 lines (40 loc) • 1.32 kB
text/coffeescript
fs = require 'fs'
archiver = require 'archiver'
path = require 'path'
module.exports = (filePaths, zipFilePath, callback = ->) ->
if typeof filePaths is 'string'
filePaths = [filePaths]
defaultZipFileName = path.basename(filePaths[0], path.extname(filePaths[0])) + '.zip'
if typeof zipFilePath is 'function'
callback = zipFilePath
zipFilePath = defaultZipFileName
archive = archiver 'zip'
archive.on 'error', callback
add = ->
filePath = filePaths.shift()
if filePath
fs.stat filePath, (err, stats) ->
if err
archive.abort()
return callback err
if stats.isDirectory()
archive.directory filePath
else
archive.file filePath, name: path.basename filePath
add()
else
fs.stat zipFilePath, (err, stats) ->
if err and err.errno isnt 34
archive.abort()
return callback err
if not err and stats.isDirectory()
zipFilePath = path.join zipFilePath, defaultZipFileName
writeSteam = fs.createWriteStream zipFilePath
writeSteam.on 'error', (err) ->
archive.abort()
callback err
writeSteam.on 'close', ->
callback null, path.resolve zipFilePath
archive.pipe writeSteam
archive.finalize()
add()