如何将Node.js中的.zip / .rar文件解压到一个文件夹中

现在我正在使用zlib和fstream一起压缩并发送到客户端,现在我需要将存档(可能包含子文件夹)解压缩到维护文件夹结构的文件夹中。 我怎么做?

有很多节点模块可以为你做到这一点。 其中之一是节点解压缩。 你可以像这样简单的提取一个.zip文件到一个目录。

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

进一步阅读: https : //github.com/EvanOxfeld/node-unzip

你可以使用这个惊人的模块http://node-machine.org/machinepack-zip

用于解压缩zip文件中的目录结构

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

//解压缩指定的.zip文件,并将解压后的文件/目录写为指定目标目录的内容。

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

为了下载远程文件并解压你可以使用这个代码:

  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 }, }); }) } 

注意:删除不必要的模块。

Rar是一个封闭的源代码软件。 你可以做到这一点的唯一方法 – 安装命令行rar(在大多数平台上可用的rar.exe或rar的linux版本)并通过以下方式调用它:

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