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

后端 未结 2 909
挽巷
挽巷 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: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()
    });
    

提交回复
热议问题