Node.js read a file in a zip without unzipping it

后端 未结 2 908
挽巷
挽巷 2021-02-04 05:16

I have a zip file (actually it\'s an epub file) I need to loop through the files in it and read them without unzipping them to the disk.

I tried to use a Node.js library

相关标签:
2条回答
  • 2021-02-04 05:53
    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 讨论(0)
  • 2021-02-04 05:55

    Since unzip seems to be abandoned, I used node-stream-zip with pretty good success.

    npm install node-stream-zip
    

    Reading files be all like:

    const StreamZip = require('node-stream-zip');
    const zip = new StreamZip({
        file: 'archive.zip',
        storeEntries: true
    });
    
    zip.on('ready', () => {
        // Take a look at the files
        console.log('Entries read: ' + zip.entriesCount);
        for (const entry of Object.values(zip.entries())) {
            const desc = entry.isDirectory ? 'directory' : `${entry.size} bytes`;
            console.log(`Entry ${entry.name}: ${desc}`);
        }
    
        // Read a file in memory
        let zipDotTxtContents = zip.entryDataSync('path/inside/zip.txt').toString('utf8');
        console.log("The content of path/inside/zip.txt is: " + zipDotTxtContents);
    
        // Do not forget to close the file once you're done
        zip.close()
    });
    
    0 讨论(0)
提交回复
热议问题