Nodejs教程
Nodejs Mysql
Nodejs MongoDB
Nodejs 对比

Node.js ZLIB

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 zlib示例1
打开Node.js命令提示符并运行以下代码:
node zlib_example1.js
Node.js zlib示例2
您会看到它将产生一个名为" input.txt"的压缩文件.gz"。
Node.js zlib示例3

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"文件中。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4