Node.jsZLib模块
Node.js Zlib模块用于提供压缩和解压缩(zip和unzip)功能。它是使用Gzip和deflate/inflate实现的。
可以使用以下命令访问zlib模块:
const zlib = require('zlib');
压缩文件示例
让无涯教程看一下一个Node.js ZLIB模块的简单示例,该模块将文件“ input.txt”压缩为“ input.txt.gz”。
文件:zlib_example1.js.
const zlib = require('zlib'); const gzip = zlib.createGzip(); const fs = require('fs'); const inp = fs.createReadStream('input.txt'); const out = fs.createWriteStream('input.txt.gz'); inp.pipe(gzip).pipe(out);
无涯教程在桌面上有一个名为"input.txt"的文本文件。

打开node.js命令提示符并运行以下代码:
node zlib_example1.js

您可以看到它将在桌面上生成名为"input.txt.gz"的压缩文件。

解压缩文件示例
让无涯教程看一下Node.js ZLIB模块的简单示例,该模块将文件“ input.txt.gz”解压缩为“ input2.txt”。
文件:zlib_example2.js.
const zlib = require('zlib'); const unzip = zlib.createUnzip(); const fs = require('fs'); const inp = fs.createReadStream('input.txt.gz'); const out = fs.createWriteStream('input2.txt'); inp.pipe(unzip).pipe(out);
node zlib_example2.js
为了很好地理解此示例,请创建具有大量数据的“ input.txt”文件。假设它有40 kb的数据。压缩该文件后,您将获得压缩文件“ input.txt.gz”的大小仅为1 kb。解压缩“ input.txt.gz”文件后,您将获得40 kb的相同数据到“ input2.txt”文件中。
祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)
精选教程推荐
👇 以下精选教程可能对您有帮助,拓展您的技术视野
暂无学习笔记,成为第一个分享的人吧!
您的笔记将帮助成千上万的学习者