How to unzip a .zip / .rar file in Node.js to a folder

I use zlib with fstream now for zipping and sending to the client. Now I need to unzip the archive (which may contain subfolders) into a folder that supports the folder structure. How to do it?

+6
source share
3 answers

There are many node modules that can do this for you. One of them is node-unzip. You can extract the .zip file to a directory as simple as this.

fs.createReadStream('path/to/archive.zip').pipe(unzip.Extract({ path: 'output/path' }));

Further reading: https://github.com/EvanOxfeld/node-unzip

+9
source

you can use this amazing module http://node-machine.org/machinepack-zip

to unzip the zip file with the directory structure inside the zip

 var Zip = require('machinepack-zip'); 

// Unzip the specified .zip file and write the unzipped files / directories as the contents of the specified destination directory.

 Zip.unzip({ source: '/Users/mikermcneil/stuff.zip', destination: '/Users/mikermcneil/my-stuff', }).exec(callbackSuccess, callbackFail ); 

to download the remote file and unzip you can use this code:

  var fs = require('fs'); var unzip = require("unzip2"); var tar = require('tar'); var zlib = require('zlib'); var path = require('path'); var mkdirp = require('mkdirp'); // used to create directory tree var request = require("request"); var http = require('http'); var zip = require("machinepack-zip"); for (var i = 0; i < _diff.length; i++) { request(constants.base_patch +"example.zip") request = http.get({ host: 'localhost', path: '/update/patchs/' + "example.zip", port: 80, headers: { 'accept-encoding': 'gzip,deflate' } }); request.on('response', (response) => { var output = fs.createWriteStream(__dirname + "/tmp/" +"example.zip"); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': response.pipe(zlib.createGunzip()).pipe(unzip.Extract({ path: __dirname })); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(unzip.Extract({ path: __dirname })); break; default: response.pipe(output); break; } }) request.on('close', function(){ zip.unzip({ source: __dirname + "/tmp/" + "example.zip", destination: __dirname, }).exec({ error: function (err){ alert("error") }, success: function (){ //delete temp folder content after finish uncompress }, }); }) } 

note: remove unnecessary modules.

+1
source

Rar is closed source software. The only way to do this is to install rar (rar.exe or the linux version of rar available on most platforms) and invoke it with this:

 var exec = require('child_process').exec; exec("rar.exe x file.rar", function (error) { if (error) { // error code here } else { // success code here } }); 
0
source

All Articles