NodeJS强大的解压ZIP 库

node-stream-zip库是一款非常棒的zip文件压缩库,使用方便,能解压非标准格式的ZIP文件,经过对比,使用起来比
hzip,unzipper,zip-local等库要方便很多,并且支持同步方法和异步方法。并且和adm-zip一样,支持解压制定文件和目录,adm-zip不能解压非标准的zip文件,例如APK文件。

功能特性

不加载整个文档到内存,内容按块读取

支持大文件

非阻塞读取,没有同步输入/输出

快速初始化

无依赖关系,没有二进制插件

内置zlib模块解压缩

deflate,deflate64,sfx,macosx / windows 内置档案支持

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 => { /*...*/ });

可用参数:

storeEntries: 默认为 true 允许使用您zip存档中的条目,否则需要使用条目事件
skipEntryNameValidation:默认为 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}`);
    }
    //读取完毕,记得关闭文件
    zip.close()
});

标准流读取一个文件

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();
});

解压文件夹时,监听事件

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) { }) - 通过条目读取数据
zip.entryDataSync(entry) -同步通过条目读取数据
zip.close()  不用的时候关闭它

github地址

https://github.com/antelle/node-stream-zip

 

上一篇 解决electron 调用cmd中文乱码
下一篇 深入理解JavaScript对象属性
applek

applek管理员

个人说明在个人中心里面设置

本月创作热力图

最新评论
Kevin
Kevin
3月6日
请教,小网站,1000ip不到,小主机,2c4g,到底 redis 还是 macached 合适啊
hfloke
hfloke
3月1日
新版本安装更新后,页面有问题哦
丙氨酸
丙氨酸
2月27日
测试
评论于关于本站
RiseForever
RiseForever
2月23日
听说新主题发布了,来测试下评论区。
李贰捌
李贰捌
12月25日
AI摘要打开了,对接的阿里云,测试成功,但是前台为什么不显示?