【问题标题】:How do I unzip a .zip/.rar file in Node.js into a folder如何将 Node.js 中的 .zip/.rar 文件解压缩到文件夹中
【发布时间】:2014-01-27 13:27:38
【问题描述】:

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

【问题讨论】:

  • 您好,请问如何将整个文件夹压缩成一个 zip 文件。我正在尝试使用 fstream.Reader({path:"E:\\d data\\electron\\Applications\\FirstApp\\js\\temp\\",type:"Directory"}) .pipe(new tar .Pack()) .pipe(zlib.Gzip()) .pipe(fstream.Writer({path:"C:\\Users\\Raina\\AppData\\Local\\Temp",file:'compressed_folder.tar .gz' }));但我收到一个错误。

标签: node.js


【解决方案1】:

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

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

延伸阅读:https://github.com/EvanOxfeld/node-unzip

【讨论】:

  • 我可以在不使用 unzip 的情况下对 zlib 做同样的事情吗?
  • @Raghav 我相信 zlib 是用于处理 GZip 而不是 Zip。
  • @gpopoteur 嗨,我知道这篇文章已经很老了,但它对我很有帮助。你能告诉我我怎么知道整个事情 fs.createReadStream('path/to/archive.zip').pipe(unzip.Extract({ path: 'output/path' }));完成?我想在它完成后做点什么:)
  • 在 zip 的内容完全提取到磁盘后,Extract 会发出“关闭”事件。
  • 我们可以给这个函数添加一个返回值吗?
【解决方案2】:

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

var exec = require('child_process').exec;

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

【讨论】:

    【解决方案3】:

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

    用于解压 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 
                        },
                    });
                })
        }
    

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

    【讨论】:

      【解决方案4】:

      使用node js解压-zip,先用npm安装:

      npm install decompress-zip --save
      

      那么你必须要求它:

      const DecompressZip = require('decompress-zip');
      

      最后你可以通过以下方式使用它:

      let unzipper = new DecompressZip( absolutePathFileZip );
      

      必须指定要提取的目录:

      unzipper.extract({
          path: pathToExtract
      }); 
      

      另外,您可以使用以下内容进行更好的控制:

      处理错误:

      unzipper.on('error', function (err) {
            console.log('event error')
       });
      

      提取所有内容时通知

      unzipper.on('extract', function (log) {
          console.log('log es', log);
      });
      

      通知解压文件的“进度”:

      unzipper.on('progress', function (fileIndex, fileCount) {
          console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);         
      });
      

      【讨论】:

        【解决方案5】:

        如果有人在寻找异步等待方式的语法:

        const request = require('request');
        const unzip = require('unzip');
        
        await new Promise(resolve =>
                    request('url')
                        .pipe(fs.createWriteStream('path/zipfilename'))
                        .on('finish', () => {
                            resolve();
                        }));
        
        await new Promise(resolve =>
                    fs.createReadStream('path/filename')
                        .pipe(unzip.Extract({ path: 'path/extractDir }))
                        .on('close', ()=>{
                            resolve()
                        }));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-05
          • 1970-01-01
          • 2013-03-09
          • 2015-04-05
          • 2021-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多