Compressing files with node.js

I needed to compress entire folders with node.js and I tried several modules until I found one that worked. The one that actually worked for me was archiver, which apparently can do TAR apart from ZIP.

To install using npm just do


npm install archiver

It's good that you can specify if you want relative paths and all those niceties. Also, it uses streams, which I'm still learning to use, but they're better than reading the whole thing in memory.

Here's how you'd use it to add everything in srcDirectory recursively:


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

var output = fs.createWriteStream(outputPath);
var zipArchive = archiver('zip');

output.on('close', function() {
    console.log('done with the zip', outputPath);
});

zipArchive.pipe(output);

zipArchive.bulk([
    { src: [ '**/*' ], cwd: srcDirectory, expand: true }
]);

zipArchive.finalize(function(err, bytes) {

    if(err) {
      throw err;
    }

    console.log('done:', base, bytes);

});

For reference purposes, I also tried adm-zip (which gulp-zip uses internally) and node-zip, none of which would produce a working ZIP file (I got CRC errors when uncompressing).