本文概述
Node.js Zlib模块用于提供压缩和解压缩(zip和unzip)功能。它使用Gzip和deflate / inflate实现。
可以使用以下命令访问zlib模块:
const zlib = require('zlib');
可以通过将源流数据通过zlib流传输到目标流中来完成文件的压缩和解压缩。
Node.js 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示例:解压缩文件
让我们看一个简单的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
现在, 你将看到” input2.txt”文件中提供了与” input.txt”相同的代码。
为了很好地理解此示例, 请创建具有大量数据的” input.txt”文件。假设它具有40 kb的数据。压缩该文件后, 你将获得压缩文件” input.txt.gz”的大小仅为1 kb。解压缩” input.txt.gz”文件后, 你将获得40 kb的相同数据到” input2.txt”文件中。
来源:
https://www.srcmini02.com/28036.html