2016-09-26 147 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 –

相關問題