NodeJS強(qiáng)大的解壓ZIP 庫
node-stream-zip庫是一款非常棒的zip文件壓縮庫,使用方便,能解壓非標(biāo)準(zhǔn)格式的ZIP文件,經(jīng)過對比,使用起來比
hzip,unzipper,zip-local等庫要方便很多,并且支持同步方法和異步方法。并且和adm-zip一樣,支持解壓制定文件和目錄,adm-zip不能解壓非標(biāo)準(zhǔn)的zip文件,例如APK文件。
功能特性
不加載整個文檔到內(nèi)存,內(nèi)容按塊讀取
支持大文件
非阻塞讀取,沒有同步輸入/輸出
快速初始化
無依賴關(guān)系,沒有二進(jìn)制插件
內(nèi)置zlib模塊解壓縮
deflate,deflate64,sfx,macosx / windows 內(nèi)置檔案支持
ZIP64支持
使用方法
安裝
npm install node-stream-zip
打開ZIP文件
const StreamZip = require('node-stream-zip'); const zip = new StreamZip({ file: 'archive.zip', storeEntries: true }); // 報錯提示 zip.on('error', err => { /*...*/ });
可用參數(shù):
storeEntries: 默認(rèn)為 true 允許使用您zip存檔中的條目,否則需要使用條目事件
skipEntryNameValidation:默認(rèn)為 true 是否檢查非法字符路徑, 例如../ 或 c:\123。
列出文件列表
zip.on('ready', () => { 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}`); } //讀取完畢,記得關(guān)閉文件 zip.close() });
標(biāo)準(zhǔn)流讀取一個文件
zip.on('ready', () => { zip.stream('path/inside/zip.txt', (err, stm) => { stm.pipe(process.stdout); stm.on('end', () => zip.close()); }); });
解壓文件到硬盤
zip.on('ready', () => { zip.extract('path/inside/zip.txt', './extracted.txt', err => { console.log(err ? 'Extract error' : 'Extracted'); zip.close(); }); });
解壓目錄到硬盤
zip.on('ready', () => { fs.mkdirSync('extracted'); zip.extract('path/inside/zip/', './extracted', err => { console.log(err ? 'Extract error' : 'Extracted'); zip.close(); }); });
解壓所有文件
zip.on('ready', () => { fs.mkdirSync('extracted'); zip.extract(null, './extracted', (err, count) => { console.log(err ? 'Extract error' : `Extracted ${count} entries`); zip.close(); }); });
同步讀取文件到變量
zip.on('ready', () => { const data = zip.entryDataSync('path/inside/zip.txt'); zip.close(); });
解壓文件夾時,監(jiān)聽事件
zip.on('extract', (entry, file) => { console.log(`Extracted ${entry.name} to ${file}`); });
加載期間為每個條目生成一個條目事件
zip.on('entry', entry => { // you can already stream this entry, // without waiting until all entry descriptions are read (suitable for very large archives) console.log(`Read entry ${entry.name}`); });
可用方法
zip.entries() - 獲取所有條目描述
zip.entry(name) - 通過名稱獲取條目描述
zip.stream(entry, function(err, stm) { }) - 通過條目讀取數(shù)據(jù)
zip.entryDataSync(entry) -同步通過條目讀取數(shù)據(jù)
zip.close()? 不用的時候關(guān)閉它
github地址
https://github.com/antelle/node-stream-zip