Need to ZIP an entire directory using Node.js

commadelimited picture commadelimited · Mar 26, 2013 · Viewed 116.4k times · Source

I need to zip an entire directory using Node.js. I'm currently using node-zip and each time the process runs it generates an invalid ZIP file (as you can see from this Github issue).

Is there another, better, Node.js option that will allow me to ZIP up a directory?

EDIT: I ended up using archiver

writeZip = function(dir,name) {
var zip = new JSZip(),
    code = zip.folder(dir),
    output = zip.generate(),
    filename = ['jsd-',name,'.zip'].join('');

fs.writeFileSync(baseDir + filename, output);
console.log('creating ' + filename);
};

sample value for parameters:

dir = /tmp/jsd-<randomstring>/
name = <randomstring>

UPDATE: For those asking about the implementation I used, here's a link to my downloader:

Answer

commadelimited picture commadelimited · Sep 13, 2013

I ended up using archiver lib. Works great.

Example

var file_system = require('fs');
var archiver = require('archiver');

var output = file_system.createWriteStream('target.zip');
var 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);

// append files from a sub-directory, putting its contents at the root of archive
archive.directory(source_dir, false);

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');

archive.finalize();