Node.js中如何创建和提取zip文件?方法介绍


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

const AdmZip = require('adm-zip');

 

const file = new AdmZip();

 

file.addLocalFile('./package.json', 'project');

file.addLocalFolder('./node_modules', 'project/node_modules');

 

const fs = require('fs');

 

fs.writeFileSync('output.zip', file.toBuffer());

可以用 file.addFile() 方法从原始 Node.js 缓冲区添加文件。以下是不在文件系统上创建文件的情况下,将包含字符串 Hello,World 的文本文件添加到 zip 文件中的方法。

1

2

3

4

5

6

7

8

9

const AdmZip = require('adm-zip');

 

const file = new AdmZip();

 

file.addFile('hello.txt', Buffer.fromString('Hello, World'));

 

const fs = require('fs');

 

fs.writeFileSync('output.zip', file.toBuffer());

使用现有文件

如果你将参数传递给 AdmZip 构造函数,则adm-zip将在给定路径下解析文件。下面是将所有内容从 output.zip 文件提取到目录 output 的方法。

1

2

3

4

5

const AdmZip = require('adm-zip');

 

const file = new AdmZip('./output.zip');

 

file.extractAllTo('./output');

也可以用 file.extractEntryTo() 从 zip 文件中提取单个文件。例如,下面是从 zip 文件中拉出 hello.txt 文件并将其写入当前目录的方法:

1

2

3

4

5

const AdmZip = require('adm-zip');

 

const file = new AdmZip('./output.zip');

 

file.extractEntryTo('hello.txt', './');

你也可以对现有文件使用 addLocalFile()addLocalFolder()addFile()

总结

zip 文件通常用于压缩。某些服务(例如AWS Lambda)要求你使用 zip 文件。幸运的是,adm-zip npm 模块使直接从 Node.js 创建和提取 zip 文件变得容易。

英文原文地址:http://thecodebarbarian.com/working-with-zip-files-in-node-js.html

作者:Valeri Karpov

更多编程相关知识,请访问:编程视频!!

以上就是Node.js中如何创建和提取zip文件?方法介绍的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

如何在macos上安装node.js和npm

nodejs接口如何传输数据?

node.js真的单线程吗?进程间如何通信?

了解一下node.js casbin

使用docker高效部署node.js应用的方法介绍

mac和windows下如何使用nvm安装和管理多个版本的node.js

2021年值得了解的8个 node.js 框架

vue刷新404的问题解决方法

npm和yarn安装node-sass的问题解决方法介绍

如何利用nvm工具来管理node版本?方法介绍

更多相关阅读请进入《node.js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...