2016-09-26 158 views
3

我有一个zip文件(实际上它是一个epub文件),我需要遍历它中的文件并读取它们,而无需将它们解压缩到磁盘。Node.js在不解压的情况下读取zip文件

我试图用Node.js的库调用JSZip但每个文件的内容存储在内存中缓冲,每当我试图将缓冲区内容进行解码,以字符串返回的内容是不可读

下面的代码我想:

const zip = new JSZip(); 
    // read a zip file 
    fs.readFile(epubFile, function (err, data) { 
     if (err) throw err; 
     zip.loadAsync(data).then(function (zip) { 
      async.eachOf(zip.files, function (content, fileName, callback) { 
       if (fileName.match(/json/)) { 
        var buf = content._data.compressedContent; 
        console.log(fileName); 
        console.log((new Buffer(buf)).toString('utf-8')); 
       } 
       callback(); 
      }, function (err) { 
       if (err) { 
        console.log(err); 
       } 
      }); 
     }); 
    }); 

回答

5
npm install unzip 

https://www.npmjs.com/package/unzip

fs.createReadStream('path/to/archive.zip') 
    .pipe(unzip.Parse()) 
    .on('entry', function (entry) { 
    var fileName = entry.path; 
    var type = entry.type; // 'Directory' or 'File' 
    var size = entry.size; 
    if (fileName === "this IS the file I'm looking for") { 
     entry.pipe(fs.createWriteStream('output/path')); 
    } else { 
     entry.autodrain(); 
    } 
    }); 
+0

你会如何使用条目作为读取流?我正在尝试将它传送给s3 –

相关问题