当前位置: 首页 > 后端技术 > Node.js

【node】zlib

时间:2023-04-03 20:47:10 Node.js

node:zlib模块提供了使用Gzip、Deflate/Inflate和Brotli实现的压缩功能。deflate算法DEFLATE是一种无损数据压缩算法,它同时使用了LZ77算法和霍夫曼编码。DEFLATE压缩和解压缩的代码可以在免费的通用压缩库zlib中找到。常见的压缩算法如下:zlib(RFC1950):简单封装deflate的格式,zlib=zlibheader+deflate+zlibtail编码的实际内容gzip(RFC1952):也执行deflate的格式gzip=gzipheader的封装+deflateencodedactualcontent+gziptailLZ77algorithmLZ77是一种基于字典的算法,将长字符串(也称为短语)编码为短标记,并在字典中用小标记替换短语,从而达到压缩的目的。也就是说,它通过用小标记替换数据中重复出现的长字符串来压缩数据。它处理的符号不一定是文本字符,而是任意大小的符号。使用压缩const{createGzip}=require('zlib');const{pipeline}=require('stream');const{createReadStream,createWriteStream}=require('fs');constgzip=createGzip();constsource=createReadStream('input.txt');constdestination=createWriteStream('input.txt.gz');pipeline(source,gzip,destination,(err)=>{if(err){console.error('发生错误:',err);process.exitCode=1;}});//或者,promise化const{promisify}=require('util');constpipe=promisify(pipeline);asyncfunctiondo_gzip(input,output){constgzip=createGzip();constsource=createReadStream(输入);constdestination=createWriteStream(输出);awaitpipe(source,gzip,destination);}do_gzip('input.txt','input.txt.gz').catch((err)=>{console.error('发生错误:',err);process.exitCode=1;});解压const{createGunzip}=require('zlib');const{pipeline}=require('stream');const{createReadStream,createWriteStream}=require('fs');constgzip=createGunzip();constsource=createReadStream('input.txt');constdestination=createWriteStream('input.txt.gz');pipeline(source,gzip,destination,(错误)=>{if(err){console.error('Anerroroccurred:',err);process.exitCode=1;}});Zlib属性和方法MethodDescriptionconstants返回一个包含Zlib常量的对象createDeflate()创建一个Deflate对象createDeflateRaw()创建一个DeflateRaw对象createGunzip()创建一个Gunzip对象createGzip()创建一个Gzip对象createInflate()创建一个Inflate对象createInflateRaw()创建一个InflateRaw对象createUnzip()创建一个Unzip对象deflate()压缩一个字符串或缓冲区,使用DeflatedeflateSync()压缩一个字符串或缓冲区,同步使用DeflatedeflateRaw()压缩字符串或缓冲区,使用DeflateRawdeflateRawSync()压缩字符串或缓冲区,同步使用DeflateRawgunzip()压缩字符串或缓冲区,使用GunzipgunzipSync()压缩字符串或缓冲区fer,syncronously,使用Gunzipgzip()压缩字符串或缓冲区,使用GzipgzipSync()压缩字符串或缓冲区,syncronously,使用Gzipinflate()使用InflateRawinflateRawSync()解压缩字符串或缓冲区使用InflateRawunzip()同步解压缩字符串或缓冲区使用UnzipunzipSync()解压缩字符串或缓冲区zlib的流从zlib/zconf.h开始,针对Node.js使用进行了修改:deflate内存要求(以字节为单位):(1<<(windowBits+2))+(1<<(memLevel+9))即:128KforwindowBits=15+128KformemLevel=8(默认值)加上几千字节对于小对象例如,要将默认内存需求从256K减少到128K,该选项应设置为:constoptions={windowBits:14,memLevel:7};然而,这通常会降低压缩性能。inflate的内存要求是(以字节为单位)1<