当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Node.js API详解之 zlib模块用法分析

Node.js API详解之 zlib模块用法分析

2020年06月14日  | 移动技术网IT编程  | 我要评论

金善雅图片,马晓晴背后高官是谁,采矿证

本文实例讲述了node.js api详解之 zlib模块用法。分享给大家供大家参考,具体如下:

node.js api详解之 zlib

zlib模块提供通过 gzip 和 deflate/inflate 实现的压缩功能,可以通过这样使用它:

const zlib = require('zlib');

压缩或者解压数据流(例如一个文件)通过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);

zlib 可以用来实现对 http 中定义的 gzip 和 deflate 内容编码机制的支持。
http 的 accept-encoding 头字段用来标记客户端接受的压缩编码。
注意: 下面给出的示例大幅简化,用以展示了基本的概念。使用 zlib 编码成本会很高, 结果应该被缓存。

// 客户端请求示例
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const request = http.get({ host: 'example.com',
              path: '/',
              port: 80,
              headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', (response) => {
 const output = fs.createwritestream('example.com_');
 switch (response.headers['content-encoding']) {
  // 或者, 只是使用 zlib.createunzip() 方法去处理这两种情况
  case 'gzip':
   response.pipe(zlib.creategunzip()).pipe(output);
   break;
  case 'deflate':
   response.pipe(zlib.createinflate()).pipe(output);
   break;
  default:
   response.pipe(output);
   break;
 }
});

// 服务端示例
// 对每一个请求运行 gzip 操作的成本是十分高昂的.
// 缓存压缩缓冲区是更加高效的方式.
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
http.createserver((request, response) => {
 const raw = fs.createreadstream('');
 let acceptencoding = request.headers['accept-encoding'];
 if (!acceptencoding) {
  acceptencoding = '';
 }
 // 注意:这不是一个合适的 accept-encoding 解析器.
 // 查阅 http://www.w3.org/protocols/rfc2616/rfc2616-sec14.html#sec14.3
 if (/\bdeflate\b/.test(acceptencoding)) {
  response.writehead(200, { 'content-encoding': 'deflate' });
  raw.pipe(zlib.createdeflate()).pipe(response);
 } else if (/\bgzip\b/.test(acceptencoding)) {
  response.writehead(200, { 'content-encoding': 'gzip' });
  raw.pipe(zlib.creategzip()).pipe(response);
 } else {
  response.writehead(200, {});
  raw.pipe(response);
 }
}).listen(1337);

constants(常量)

说明:

这些被定义在 zlib.h 的全部常量同时也被定义在 require('zlib').constants 常量上.
注意: 以前, 可以直接从 require('zlib') 中获取到这些常量, 例如 zlib.z_no_flush.
目前仍然可以从模块中直接访问这些常量, 但是不推荐使用.

demo:

const zlib = require('zlib');
// 可接受的 flush 值.
zlib.constants.z_no_flush
zlib.constants.z_partial_flush
zlib.constants.z_sync_flush
zlib.constants.z_full_flush
zlib.constants.z_finish
zlib.constants.z_block
zlib.constants.z_trees
// 返回压缩/解压函数的返回值. 发送错误时为负值, 正值用于特殊但正常的事件.
zlib.constants.z_ok
zlib.constants.z_stream_end
zlib.constants.z_need_dict
zlib.constants.z_errno
zlib.constants.z_stream_error
zlib.constants.z_data_error
zlib.constants.z_mem_error
zlib.constants.z_buf_error
zlib.constants.z_version_error
// 压缩等级.
zlib.constants.z_no_compression
zlib.constants.z_best_speed
zlib.constants.z_best_compression
zlib.constants.z_default_compression
// 压缩策略
zlib.constants.z_filtered
zlib.constants.z_huffman_only
zlib.constants.z_rle
zlib.constants.z_fixed
zlib.constants.z_default_strategy

options

说明:

每一个类都有一个 options 对象. 所有的选项都是可选的.
注意:一些选项只与压缩相关, 会被解压类忽视.

demo:

const zlib = require('zlib');
const options = {
 flush: zlib.constants.z_no_flush,
 finishflush: zlib.constants.z_finish,
 chunksize: 16*1024,
 windowbits 2, //值在8..15的范围内,这个参数的值越大,内存使用率越高,压缩效果越好。如果使用deflateinit,则默认值为15
 level: 6,  //(压缩级别,值在0-9之间,1速度最快,9压缩比最大,各自折中取值6较为合适。仅压缩有效)
 memlevel: 8,  // (指定多少内存应该内部压缩状态进行分配,1是最小内存速度慢压缩比低。9是最大内存,速度最快。默认值为8。仅压缩有效)
 strategy: 7, // (用于调整压缩算法,仅压缩有效)
 dictionary: ' | | ',  // (仅解压有效,默认值为空字典)
 info: true  //(如果true,返回一个buffer对象和engine)
}

zlib.constants

说明:

提供一个列举出 zlib 相关常数的对象。

demo:

const zlib = require('zlib');
console.log(zlib.constants);
// { z_no_flush: 0,
//  z_partial_flush: 1,
//  z_sync_flush: 2,
//  z_full_flush: 3,
//  z_finish: 4,
//  z_block: 5,
//  z_ok: 0,
//  z_stream_end: 1,
//  z_need_dict: 2,
//  z_errno: -1,
//  z_stream_error: -2,
//  z_data_error: -3,
//  z_mem_error: -4,
//  z_buf_error: -5,
//  z_version_error: -6,
//  z_no_compression: 0,
//  z_best_speed: 1,
//  z_best_compression: 9,
//  z_default_compression: -1,
//  z_filtered: 1,
//  z_huffman_only: 2,
//  z_rle: 3,
//  z_fixed: 4,
//  z_default_strategy: 0,
//  zlib_vernum: 4784,
//  deflate: 1,
//  inflate: 2,
//  gzip: 3,
//  gunzip: 4,
//  deflateraw: 5,
//  inflateraw: 6,
//  unzip: 7,
//  z_min_windowbits: 8,
//  z_max_windowbits: 15,
//  z_default_windowbits: 15,
//  z_min_chunk: 64,
//  z_max_chunk: infinity,
//  z_default_chunk: 16384,
//  z_min_memlevel: 1,
//  z_max_memlevel: 9,
//  z_default_memlevel: 8,
//  z_min_level: -1,
//  z_max_level: 9,
//  z_default_level: -1 }

zlib.createdeflate(options)

说明:

创建并返回一个带有给定 options 的新的 deflate 对象。
可以使用 deflate 压缩数据。

demo:

const zlib = require('zlib');
const deflate = zlib.createdeflate();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(deflate) );
// deflate {
//  _readablestate:
//  readablestate { ... },
//  bytesread: 0,
//  _handle: zlib { jsref: [circular], onerror: [function: zlibonerror] },
//  _haderror: false,
//  _writestate: uint32array [ 0, 0 ],
//  _outbuffer: ,
//  _outoffset: 0,
//  _level: -1,
//  _strategy: 0,
//  _chunksize: 16384,
//  _flushflag: 0,
//  _scheduledflushflag: 0,
//  _origflushflag: 0,
//  _finishflushflag: 4,
//  _info: undefined }

zlib.createinflate(options)

说明:

创建并返回一个带有给定 options 的新的 inflate 对象。
inflate 用于解压一个 deflate 流。

demo:

const zlib = require('zlib');
const deflate = zlib.createdeflate();
const inflate = zlib.createinflate();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(deflate).pipe(inflate) );

zlib.createdeflateraw(options)

说明:

创建并返回一个带有给定 options 的新的 deflateraw 对象.
使用 deflate 压缩数据,并且不附加一个 zlib 头。

demo:

const zlib = require('zlib');
const deflateraw = zlib.createdeflateraw();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(deflateraw) );

zlib.createinflateraw(options)

说明:

创建并返回一个带有给定 options 的新的 inflateraw 对象。
inflateraw 用于解压一个 raw deflate 流。

demo:

const zlib = require('zlib');
const deflateraw = zlib.createdeflateraw();
const inflateraw = zlib.createinflateraw();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(deflateraw).pipe(inflateraw) );

zlib.creategzip(options)

说明:

创建并返回一个带有给定 options 的新的 gunzip 对象。
使用 gzip 压缩数据。

demo:

const zlib = require('zlib');
const gzip = zlib.creategzip();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(gzip) );

zlib.creategunzip(options)

说明:

创建并返回一个带有给定 options 的新的 gunzip 对象
使用gunzip解压缩 gzip 流。

demo:

const zlib = require('zlib');
const gzip = zlib.creategzip();
const gunzip = zlib.creategunzip();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(gzip).pipe(gunzip) );

zlib.createunzip(options)

说明:

创建并返回一个带有给定 options 的新的 unzip 对象。
unzip 对象通过自动检测头信息解压 gzip 或者 deflate 压缩的流.

demo:

const zlib = require('zlib');
const gzip = zlib.creategzip();
const unzip = zlib.createunzip();
const fs = require('fs');
const inp = fs.createreadstream('a.js');
console.log( inp.pipe(gzip).pipe(unzip) );

convenience methods(简便用法)

说明:

上面我们介绍了各个压缩类的使用。下面介绍一些对应的简便用法。
所有这些方法都将 buffer, [typearray], dataview, 或者字符串作为第一个 参数,
一个回调函数作为可选的第二个参数提供给 zlib 类, 会在 callback(error, result) 中调用.
每一个方法相对应的都有一个接受相同参数, 但是没有回调的 *sync 版本.
zlib.deflate(buffer [,options],callback)
zlib.deflatesync(buffer [,options])
zlib.inflate(buffer [,options],callback)
zlib.inflatesync(buffer [,options])
zlib.deflateraw(buffer [,options],callback)
zlib.deflaterawsync(buffer [,options])
zlib.inflateraw(buffer [,options],callback)
zlib.inflaterawsync(buffer [,options])
zlib.gzip(buffer [,options],callback)
zlib.gzipsync(buffer [,options])
zlib.gunzip(buffer [,options],callback)
zlib.gunzipsync(buffer [,options])
zlib.unzip(buffer [,options],callback)
zlib.unzipsync(buffer [,options])

使用方式如下:

demo:

const input = '.................................';
zlib.deflate(input, (err, buffer) => {
 if (!err) {
  console.log(buffer.tostring('base64'));
 } else {
  // 错误处理
 }
});
const buffer = buffer.from('ejzt0ymaagtvbe8=', 'base64');
zlib.unzip(buffer, (err, buffer) => {
 if (!err) {
  console.log(buffer.tostring());
 } else {
  // 错误处理
 }
});

希望本文所述对大家node.js程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网