Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip archives in node.js

Tags:

node.js

zip

I want to create a zip archive and unzip it in node.js.

I can't find any node implementation.

like image 738
msikora Avatar asked Apr 22 '11 09:04

msikora


People also ask

How do I zip a folder in node JS?

To zip an entire directory using Node. js, we can use the archiver package. const fs = require('fs'); const archiver = require('archiver'); const output = fs. createWriteStream('target.

What is ADM-zip?

ADM-ZIP is a pure JavaScript implementation for zip data compression for NodeJS.


2 Answers

I ended up doing it like this (I'm using Express). I'm creating a ZIP that contains all the files on a given directory (SCRIPTS_PATH).

I've only tested this on Mac OS X Lion, but I guess it'll work just fine on Linux and Windows with Cygwin installed.

var spawn = require('child_process').spawn; app.get('/scripts/archive', function(req, res) {     // Options -r recursive -j ignore directory info - redirect to stdout     var zip = spawn('zip', ['-rj', '-', SCRIPTS_PATH]);      res.contentType('zip');      // Keep writing stdout to res     zip.stdout.on('data', function (data) {         res.write(data);     });      zip.stderr.on('data', function (data) {         // Uncomment to see the files being added         // console.log('zip stderr: ' + data);     });      // End the response on zip exit     zip.on('exit', function (code) {         if(code !== 0) {             res.statusCode = 500;             console.log('zip process exited with code ' + code);             res.end();         } else {             res.end();         }     }); }); 
like image 117
Eliseo Soto Avatar answered Sep 24 '22 09:09

Eliseo Soto


node-core has built in zip features: http://nodejs.org/api/zlib.html

Use them:

var zlib = require('zlib'); var gzip = zlib.createGzip(); var fs = require('fs'); var inp = fs.createReadStream('input.txt'); var out = fs.createWriteStream('input.txt.gz');  inp.pipe(gzip).pipe(out); 
like image 30
MateodelNorte Avatar answered Sep 26 '22 09:09

MateodelNorte