Nodejs教程-Node.js ZLIB

Node.js的Zlib模块用于提供压缩和解压缩(压缩和解压缩)功能。它使用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"文件。假设它有40kb的数据。压缩此文件后,压缩文件"input.txt.gz"的大小仅为1kb。在解压缩"input.txt.gz"文件后,您将在"input2.txt"文件中获得40kb的相同数据。