Node.js v25.0.0 文档
- Node.js v25.0.0
-
目录
- Zlib
- 线程池的使用和性能考量
- 压缩 HTTP 请求和响应
- 内存使用调优
- 刷新(Flushing)
- 常量
- 类:
Options
- 类:
BrotliOptions
- 类:
zlib.BrotliCompress
- 类:
zlib.BrotliDecompress
- 类:
zlib.Deflate
- 类:
zlib.DeflateRaw
- 类:
zlib.Gunzip
- 类:
zlib.Gzip
- 类:
zlib.Inflate
- 类:
zlib.InflateRaw
- 类:
zlib.Unzip
- 类:
zlib.ZlibBase
- 类:
ZstdOptions
- 类:
zlib.ZstdCompress
- 类:
zlib.ZstdDecompress
zlib.constants
zlib.crc32(data[, value])
zlib.createBrotliCompress([options])
zlib.createBrotliDecompress([options])
zlib.createDeflate([options])
zlib.createDeflateRaw([options])
zlib.createGunzip([options])
zlib.createGzip([options])
zlib.createInflate([options])
zlib.createInflateRaw([options])
zlib.createUnzip([options])
zlib.createZstdCompress([options])
zlib.createZstdDecompress([options])
- 便捷方法
zlib.brotliCompress(buffer[, options], callback)
zlib.brotliCompressSync(buffer[, options])
zlib.brotliDecompress(buffer[, options], callback)
zlib.brotliDecompressSync(buffer[, options])
zlib.deflate(buffer[, options], callback)
zlib.deflateSync(buffer[, options])
zlib.deflateRaw(buffer[, options], callback)
zlib.deflateRawSync(buffer[, options])
zlib.gunzip(buffer[, options], callback)
zlib.gunzipSync(buffer[, options])
zlib.gzip(buffer[, options], callback)
zlib.gzipSync(buffer[, options])
zlib.inflate(buffer[, options], callback)
zlib.inflateSync(buffer[, options])
zlib.inflateRaw(buffer[, options], callback)
zlib.inflateRawSync(buffer[, options])
zlib.unzip(buffer[, options], callback)
zlib.unzipSync(buffer[, options])
zlib.zstdCompress(buffer[, options], callback)
zlib.zstdCompressSync(buffer[, options])
zlib.zstdDecompress(buffer[, options], callback)
zlib.zstdDecompressSync(buffer[, options])
- Zlib
-
索引
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:module
API - 模块:包
- 模块:TypeScript
- 网络
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- 其他版本
- 选项
Zlib#
源代码: lib/zlib.js
node:zlib
模块提供了使用 Gzip、Deflate/Inflate、Brotli 和 Zstd 实现的压缩功能。
要访问它
import zlib from 'node:zlib';
const zlib = require('node:zlib');
压缩和解压缩是围绕 Node.js 流 API 构建的。
压缩或解压缩流(例如文件)可以通过将源流通过 zlib
Transform
流管道传输到目标流来完成
import {
createReadStream,
createWriteStream,
} from 'node:fs';
import process from 'node:process';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream';
const gzip = createGzip();
const source = createReadStream('input.txt');
const destination = createWriteStream('input.txt.gz');
pipeline(source, gzip, destination, (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
});
const {
createReadStream,
createWriteStream,
} = require('node:fs');
const process = require('node:process');
const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream');
const gzip = createGzip();
const source = createReadStream('input.txt');
const destination = createWriteStream('input.txt.gz');
pipeline(source, gzip, destination, (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
});
或者,使用 Promise pipeline
API
import {
createReadStream,
createWriteStream,
} from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
async function do_gzip(input, output) {
const gzip = createGzip();
const source = createReadStream(input);
const destination = createWriteStream(output);
await pipeline(source, gzip, destination);
}
await do_gzip('input.txt', 'input.txt.gz');
const {
createReadStream,
createWriteStream,
} = require('node:fs');
const process = require('node:process');
const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream/promises');
async function do_gzip(input, output) {
const gzip = createGzip();
const source = createReadStream(input);
const destination = createWriteStream(output);
await pipeline(source, gzip, destination);
}
do_gzip('input.txt', 'input.txt.gz')
.catch((err) => {
console.error('An error occurred:', err);
process.exitCode = 1;
});
也可以在单个步骤中压缩或解压缩数据
import process from 'node:process';
import { Buffer } from 'node:buffer';
import { deflate, unzip } from 'node:zlib';
const input = '.................................';
deflate(input, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString('base64'));
});
const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString());
});
// Or, Promisified
import { promisify } from 'node:util';
const do_unzip = promisify(unzip);
const unzippedBuffer = await do_unzip(buffer);
console.log(unzippedBuffer.toString());
const { deflate, unzip } = require('node:zlib');
const input = '.................................';
deflate(input, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString('base64'));
});
const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString());
});
// Or, Promisified
const { promisify } = require('node:util');
const do_unzip = promisify(unzip);
do_unzip(buffer)
.then((buf) => console.log(buf.toString()))
.catch((err) => {
console.error('An error occurred:', err);
process.exitCode = 1;
});
线程池的使用和性能考量#
除了明确同步的 API 外,所有 zlib
API 都使用 Node.js 的内部线程池。这可能会在某些应用程序中导致意想不到的效果和性能限制。
同时创建和使用大量的 zlib 对象会导致严重的内存碎片。
import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';
const payload = Buffer.from('This is some data');
// WARNING: DO NOT DO THIS!
for (let i = 0; i < 30000; ++i) {
zlib.deflate(payload, (err, buffer) => {});
}
const zlib = require('node:zlib');
const payload = Buffer.from('This is some data');
// WARNING: DO NOT DO THIS!
for (let i = 0; i < 30000; ++i) {
zlib.deflate(payload, (err, buffer) => {});
}
在前面的例子中,同时创建了 30,000 个 deflate 实例。由于某些操作系统处理内存分配和释放的方式,这可能会导致严重的内存碎片。
强烈建议缓存压缩操作的结果,以避免重复工作。
压缩 HTTP 请求和响应#
node:zlib
模块可用于实现对 HTTP 定义的 gzip
、deflate
、br
和 zstd
内容编码机制的支持。
HTTP Accept-Encoding
标头用于 HTTP 请求中,以标识客户端接受的压缩编码。而 Content-Encoding
标头用于标识实际应用于消息的压缩编码。
下面给出的示例被大幅简化,以展示基本概念。使用 zlib
编码可能成本很高,其结果应该被缓存。有关 zlib
使用中涉及的速度/内存/压缩权衡的更多信息,请参阅内存使用调优。
// Client request example
import fs from 'node:fs';
import zlib from 'node:zlib';
import http from 'node:http';
import process from 'node:process';
import { pipeline } from 'node:stream';
const request = http.get({ host: 'example.com',
path: '/',
port: 80,
headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
request.on('response', (response) => {
const output = fs.createWriteStream('example.com_index.html');
const onError = (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
};
switch (response.headers['content-encoding']) {
case 'br':
pipeline(response, zlib.createBrotliDecompress(), output, onError);
break;
// Or, just use zlib.createUnzip() to handle both of the following cases:
case 'gzip':
pipeline(response, zlib.createGunzip(), output, onError);
break;
case 'deflate':
pipeline(response, zlib.createInflate(), output, onError);
break;
default:
pipeline(response, output, onError);
break;
}
});
// Client request example
const zlib = require('node:zlib');
const http = require('node:http');
const fs = require('node:fs');
const { pipeline } = require('node:stream');
const request = http.get({ host: 'example.com',
path: '/',
port: 80,
headers: { 'Accept-Encoding': 'br,gzip,deflate,zstd' } });
request.on('response', (response) => {
const output = fs.createWriteStream('example.com_index.html');
const onError = (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
};
switch (response.headers['content-encoding']) {
case 'br':
pipeline(response, zlib.createBrotliDecompress(), output, onError);
break;
// Or, just use zlib.createUnzip() to handle both of the following cases:
case 'gzip':
pipeline(response, zlib.createGunzip(), output, onError);
break;
case 'deflate':
pipeline(response, zlib.createInflate(), output, onError);
break;
case 'zstd':
pipeline(response, zlib.createZstdDecompress(), output, onError);
break;
default:
pipeline(response, output, onError);
break;
}
});
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
import zlib from 'node:zlib';
import http from 'node:http';
import fs from 'node:fs';
import { pipeline } from 'node:stream';
http.createServer((request, response) => {
const raw = fs.createReadStream('index.html');
// Store both a compressed and an uncompressed version of the resource.
response.setHeader('Vary', 'Accept-Encoding');
const acceptEncoding = request.headers['accept-encoding'] || '';
const onError = (err) => {
if (err) {
// If an error occurs, there's not much we can do because
// the server has already sent the 200 response code and
// some amount of data has already been sent to the client.
// The best we can do is terminate the response immediately
// and log the error.
response.end();
console.error('An error occurred:', err);
}
};
// Note: This is not a conformant accept-encoding parser.
// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (/\bdeflate\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'deflate' });
pipeline(raw, zlib.createDeflate(), response, onError);
} else if (/\bgzip\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'gzip' });
pipeline(raw, zlib.createGzip(), response, onError);
} else if (/\bbr\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'br' });
pipeline(raw, zlib.createBrotliCompress(), response, onError);
} else {
response.writeHead(200, {});
pipeline(raw, response, onError);
}
}).listen(1337);
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
const zlib = require('node:zlib');
const http = require('node:http');
const fs = require('node:fs');
const { pipeline } = require('node:stream');
http.createServer((request, response) => {
const raw = fs.createReadStream('index.html');
// Store both a compressed and an uncompressed version of the resource.
response.setHeader('Vary', 'Accept-Encoding');
const acceptEncoding = request.headers['accept-encoding'] || '';
const onError = (err) => {
if (err) {
// If an error occurs, there's not much we can do because
// the server has already sent the 200 response code and
// some amount of data has already been sent to the client.
// The best we can do is terminate the response immediately
// and log the error.
response.end();
console.error('An error occurred:', err);
}
};
// Note: This is not a conformant accept-encoding parser.
// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (/\bdeflate\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'deflate' });
pipeline(raw, zlib.createDeflate(), response, onError);
} else if (/\bgzip\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'gzip' });
pipeline(raw, zlib.createGzip(), response, onError);
} else if (/\bbr\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'br' });
pipeline(raw, zlib.createBrotliCompress(), response, onError);
} else if (/\bzstd\b/.test(acceptEncoding)) {
response.writeHead(200, { 'Content-Encoding': 'zstd' });
pipeline(raw, zlib.createZstdCompress(), response, onError);
} else {
response.writeHead(200, {});
pipeline(raw, response, onError);
}
}).listen(1337);
默认情况下,zlib
方法在解压截断数据时会抛出错误。但是,如果已知数据不完整,或者希望只检查压缩文件的开头部分,可以通过更改用于解压最后一块输入数据的刷新方法来抑制默认的错误处理
// This is a truncated version of the buffer from the above examples
const buffer = Buffer.from('eJzT0yMA', 'base64');
zlib.unzip(
buffer,
// For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
// For Zstd, the equivalent is zlib.constants.ZSTD_e_flush.
{ finishFlush: zlib.constants.Z_SYNC_FLUSH },
(err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString());
});
这不会改变其他抛出错误情况下的行为,例如输入数据格式无效时。使用此方法,将无法确定输入是过早结束还是缺少完整性检查,因此需要手动检查解压结果是否有效。
内存使用调优#
对于基于 zlib 的流#
摘自 zlib/zconf.h
,为 Node.js 使用进行了修改
deflate 的内存需求(以字节为单位)为:
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
即:windowBits
= 15 时为 128K + memLevel
= 8(默认值)时为 128K,外加几千字节用于小对象。
例如,要将默认内存需求从 256K 减少到 128K,应将选项设置为:
const options = { windowBits: 14, memLevel: 7 };
然而,这通常会降低压缩效果。
inflate 的内存需求(以字节为单位)为 1 << windowBits
。即,windowBits
= 15(默认值)时为 32K,外加几千字节用于小对象。
除此之外,还有一个大小为 chunkSize
(默认为 16K)的单个内部输出板缓冲区。
zlib
压缩的速度受 level
设置的影响最为显著。较高的级别会带来更好的压缩效果,但完成时间更长。较低的级别压缩效果较差,但速度快得多。
总的来说,更高的内存使用选项意味着 Node.js 需要对 zlib
进行更少的调用,因为它能够在每次 write
操作中处理更多的数据。因此,这是影响速度的另一个因素,但代价是内存使用量。
刷新(Flushing)#
在压缩流上调用 .flush()
会使 zlib
返回当前尽可能多的输出。这可能会以降低压缩质量为代价,但在需要尽快获得数据时非常有用。
在下面的示例中,flush()
用于将部分压缩的 HTTP 响应写入客户端:
import zlib from 'node:zlib';
import http from 'node:http';
import { pipeline } from 'node:stream';
http.createServer((request, response) => {
// For the sake of simplicity, the Accept-Encoding checks are omitted.
response.writeHead(200, { 'content-encoding': 'gzip' });
const output = zlib.createGzip();
let i;
pipeline(output, response, (err) => {
if (err) {
// If an error occurs, there's not much we can do because
// the server has already sent the 200 response code and
// some amount of data has already been sent to the client.
// The best we can do is terminate the response immediately
// and log the error.
clearInterval(i);
response.end();
console.error('An error occurred:', err);
}
});
i = setInterval(() => {
output.write(`The current time is ${Date()}\n`, () => {
// The data has been passed to zlib, but the compression algorithm may
// have decided to buffer the data for more efficient compression.
// Calling .flush() will make the data available as soon as the client
// is ready to receive it.
output.flush();
});
}, 1000);
}).listen(1337);
const zlib = require('node:zlib');
const http = require('node:http');
const { pipeline } = require('node:stream');
http.createServer((request, response) => {
// For the sake of simplicity, the Accept-Encoding checks are omitted.
response.writeHead(200, { 'content-encoding': 'gzip' });
const output = zlib.createGzip();
let i;
pipeline(output, response, (err) => {
if (err) {
// If an error occurs, there's not much we can do because
// the server has already sent the 200 response code and
// some amount of data has already been sent to the client.
// The best we can do is terminate the response immediately
// and log the error.
clearInterval(i);
response.end();
console.error('An error occurred:', err);
}
});
i = setInterval(() => {
output.write(`The current time is ${Date()}\n`, () => {
// The data has been passed to zlib, but the compression algorithm may
// have decided to buffer the data for more efficient compression.
// Calling .flush() will make the data available as soon as the client
// is ready to receive it.
output.flush();
});
}, 1000);
}).listen(1337);
常量#
zlib 常量#
所有在 zlib.h
中定义的常量也都在 require('node:zlib').constants
上定义。在正常操作过程中,不需要使用这些常量。记录它们的目的是为了让它们的存在不至于令人意外。本节几乎直接摘自 zlib 文档。
以前,这些常量可以直接从 require('node:zlib')
获得,例如 zlib.Z_NO_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_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
Brotli 常量#
对于基于 Brotli 的流,有几个选项和其他常量可用:
刷新操作#
以下值是 Brotli 流的有效刷新操作:
zlib.constants.BROTLI_OPERATION_PROCESS
(所有操作的默认值)zlib.constants.BROTLI_OPERATION_FLUSH
(调用.flush()
时的默认值)zlib.constants.BROTLI_OPERATION_FINISH
(最后一个数据块的默认值)zlib.constants.BROTLI_OPERATION_EMIT_METADATA
- 在 Node.js 上下文中,这个特定的操作可能很难使用,因为流层使其难以知道哪些数据将最终进入此帧。此外,目前没有通过 Node.js API 使用此数据的方法。
压缩器选项#
可以在 Brotli 编码器上设置几个选项,影响压缩效率和速度。键和值都可以作为 zlib.constants
对象的属性来访问。
最重要的选项是:
BROTLI_PARAM_MODE
BROTLI_MODE_GENERIC
(默认)BROTLI_MODE_TEXT
,为 UTF-8 文本调整BROTLI_MODE_FONT
,为 WOFF 2.0 字体调整
BROTLI_PARAM_QUALITY
- 范围从
BROTLI_MIN_QUALITY
到BROTLI_MAX_QUALITY
,默认值为BROTLI_DEFAULT_QUALITY
。
- 范围从
BROTLI_PARAM_SIZE_HINT
- 表示预期输入大小的整数值;对于未知输入大小,默认为
0
。
- 表示预期输入大小的整数值;对于未知输入大小,默认为
以下标志可用于对压缩算法和内存使用进行高级控制和调优:
BROTLI_PARAM_LGWIN
- 范围从
BROTLI_MIN_WINDOW_BITS
到BROTLI_MAX_WINDOW_BITS
,默认值为BROTLI_DEFAULT_WINDOW
,如果设置了BROTLI_PARAM_LARGE_WINDOW
标志,则最高可达BROTLI_LARGE_MAX_WINDOW_BITS
。
- 范围从
BROTLI_PARAM_LGBLOCK
- 范围从
BROTLI_MIN_INPUT_BLOCK_BITS
到BROTLI_MAX_INPUT_BLOCK_BITS
。
- 范围从
BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING
- 一个布尔标志,通过牺牲压缩率来提高解压缩速度。
BROTLI_PARAM_LARGE_WINDOW
- 一个布尔标志,启用“大窗口 Brotli”模式(与 RFC 7932 中标准化的 Brotli 格式不兼容)。
BROTLI_PARAM_NPOSTFIX
- 范围从
0
到BROTLI_MAX_NPOSTFIX
。
- 范围从
BROTLI_PARAM_NDIRECT
- 范围从
0
到15 << NPOSTFIX
,步长为1 << NPOSTFIX
。
- 范围从
Zstd 常量#
对于基于 Zstd 的流,有几个选项和其他常量可用:
刷新操作#
以下值是 Zstd 流的有效刷新操作:
zlib.constants.ZSTD_e_continue
(所有操作的默认值)zlib.constants.ZSTD_e_flush
(调用.flush()
时的默认值)zlib.constants.ZSTD_e_end
(最后一个数据块的默认值)
压缩器选项#
可以在 Zstd 编码器上设置几个选项,影响压缩效率和速度。键和值都可以作为 zlib.constants
对象的属性来访问。
最重要的选项是:
ZSTD_c_compressionLevel
- 根据预定义的 cLevel 表设置压缩参数。默认级别是 ZSTD_CLEVEL_DEFAULT==3。
ZSTD_c_strategy
- 选择压缩策略。
- 可能的值列在下面的策略选项部分。
策略选项#
以下常量可用作 ZSTD_c_strategy
参数的值:
zlib.constants.ZSTD_fast
zlib.constants.ZSTD_dfast
zlib.constants.ZSTD_greedy
zlib.constants.ZSTD_lazy
zlib.constants.ZSTD_lazy2
zlib.constants.ZSTD_btlazy2
zlib.constants.ZSTD_btopt
zlib.constants.ZSTD_btultra
zlib.constants.ZSTD_btultra2
示例
const stream = zlib.createZstdCompress({
params: {
[zlib.constants.ZSTD_c_strategy]: zlib.constants.ZSTD_btultra,
},
});
承诺的源大小(Pledged Source Size)#
可以通过 opts.pledgedSrcSize
指定未压缩输入的预期总大小。如果输入结束时大小不匹配,压缩将失败,错误码为 ZSTD_error_srcSize_wrong
。
解压缩器选项#
这些高级选项可用于控制解压缩:
ZSTD_d_windowLogMax
- 选择一个大小限制(以 2 的幂表示),超过该限制,流式 API 将拒绝分配内存缓冲区,以保护主机免受不合理的内存需求。
类:Options
#
每个基于 zlib 的类都接受一个 options
对象。所有选项都不是必需的。
一些选项仅在压缩时相关,并被解压缩类忽略。
flush
<integer> 默认:zlib.constants.Z_NO_FLUSH
finishFlush
<integer> 默认:zlib.constants.Z_FINISH
chunkSize
<integer> 默认:16 * 1024
windowBits
<integer>level
<integer> (仅压缩)memLevel
<integer> (仅压缩)strategy
<integer> (仅压缩)dictionary
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> (仅 deflate/inflate,默认为空字典)info
<boolean> (如果为true
,返回一个包含buffer
和engine
的对象。)maxOutputLength
<integer> 在使用便捷方法时限制输出大小。默认:buffer.kMaxLength
有关更多信息,请参阅 deflateInit2
和 inflateInit2
文档。
类:BrotliOptions
#
每个基于 Brotli 的类都接受一个 options
对象。所有选项都是可选的。
flush
<integer> 默认:zlib.constants.BROTLI_OPERATION_PROCESS
finishFlush
<integer> 默认:zlib.constants.BROTLI_OPERATION_FINISH
chunkSize
<integer> 默认:16 * 1024
params
<Object> 包含索引化 Brotli 参数的键值对象。maxOutputLength
<integer> 在使用便捷方法时限制输出大小。默认:buffer.kMaxLength
info
<boolean> 如果为true
,返回一个包含buffer
和engine
的对象。默认:false
例如:
const stream = zlib.createBrotliCompress({
chunkSize: 32 * 1024,
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: 4,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size,
},
});
类:zlib.BrotliCompress
#
- 继承自:
ZlibBase
使用 Brotli 算法压缩数据。
类:zlib.BrotliDecompress
#
- 继承自:
ZlibBase
使用 Brotli 算法解压缩数据。
类:zlib.Deflate
#
- 继承自:
ZlibBase
使用 deflate 压缩数据。
类:zlib.DeflateRaw
#
- 继承自:
ZlibBase
使用 deflate 压缩数据,并且不附加 zlib
标头。
类:zlib.Gunzip
#
- 继承自:
ZlibBase
解压缩 gzip 流。
类:zlib.Gzip
#
- 继承自:
ZlibBase
使用 gzip 压缩数据。
类:zlib.Inflate
#
- 继承自:
ZlibBase
解压缩 deflate 流。
类:zlib.InflateRaw
#
- 继承自:
ZlibBase
解压缩原始 deflate 流。
类:zlib.Unzip
#
- 继承自:
ZlibBase
通过自动检测标头来解压缩 Gzip 或 Deflate 压缩的流。
类:zlib.ZlibBase
#
- 继承自:
stream.Transform
未由 node:zlib
模块导出。在此处记录它是因为它是压缩/解压缩类的基类。
该类继承自 stream.Transform
,允许 node:zlib
对象在管道和类似的流操作中使用。
zlib.flush([kind, ]callback)
#
kind
默认: 对于基于 zlib 的流为zlib.constants.Z_FULL_FLUSH
,对于基于 Brotli 的流为zlib.constants.BROTLI_OPERATION_FLUSH
。callback
<Function>
刷新待处理数据。不要轻率地调用此方法,过早的刷新会对压缩算法的效率产生负面影响。
调用此方法仅刷新内部 zlib
状态中的数据,并不会在流级别执行任何类型的刷新。相反,它的行为类似于对 .write()
的正常调用,即它将被排在其他待处理的写入之后,并且只有在从流中读取数据时才会产生输出。
zlib.params(level, strategy, callback)
#
level
<integer>strategy
<integer>callback
<Function>
此函数仅适用于基于 zlib 的流,即不适用于 Brotli。
动态更新压缩级别和压缩策略。仅适用于 deflate 算法。
zlib.reset()
#
将压缩器/解压缩器重置为出厂默认设置。仅适用于 inflate 和 deflate 算法。
类:ZstdOptions
#
每个基于 Zstd 的类都接受一个 options
对象。所有选项都是可选的。
flush
<integer> 默认:zlib.constants.ZSTD_e_continue
finishFlush
<integer> 默认:zlib.constants.ZSTD_e_end
chunkSize
<integer> 默认:16 * 1024
params
<Object> 包含索引化 Zstd 参数的键值对象。maxOutputLength
<integer> 在使用便捷方法时限制输出大小。默认:buffer.kMaxLength
info
<boolean> 如果为true
,返回一个包含buffer
和engine
的对象。默认:false
dictionary
<Buffer> 可选字典,用于在压缩或解压缩与字典具有共同模式的数据时提高压缩效率。
例如:
const stream = zlib.createZstdCompress({
chunkSize: 32 * 1024,
params: {
[zlib.constants.ZSTD_c_compressionLevel]: 10,
[zlib.constants.ZSTD_c_checksumFlag]: 1,
},
});
类:zlib.ZstdCompress
#
使用 Zstd 算法压缩数据。
类:zlib.ZstdDecompress
#
使用 Zstd 算法解压缩数据。
zlib.constants
#
提供一个枚举 Zlib 相关常量的对象。
zlib.crc32(data[, value])
#
data
<string> | <Buffer> | <TypedArray> | <DataView> 当data
是字符串时,它将被编码为 UTF-8 后用于计算。value
<integer> 一个可选的起始值。它必须是一个 32 位无符号整数。默认:0
- 返回:<integer> 一个包含校验和的 32 位无符号整数。
计算 data
的 32 位循环冗余校验 (Cyclic Redundancy Check) 校验和。如果指定了 value
,它将用作校验和的起始值,否则使用 0 作为起始值。
CRC 算法旨在计算校验和并检测数据传输中的错误。它不适用于加密认证。
为了与其他 API 保持一致,如果 data
是一个字符串,它将在计算前被编码为 UTF-8。如果用户只使用 Node.js 来计算和匹配校验和,这与默认使用 UTF-8 编码的其他 API 配合得很好。
一些第三方 JavaScript 库基于 str.charCodeAt()
计算字符串的校验和,以便它可以在浏览器中运行。如果用户想匹配在浏览器中用这类库计算的校验和,如果该库也能在 Node.js 中运行,那么最好在 Node.js 中使用同一个库。如果用户必须使用 zlib.crc32()
来匹配由这类第三方库生成的校验和:
- 如果该库接受
Uint8Array
作为输入,请在浏览器中使用TextEncoder
将字符串编码为 UTF-8 的Uint8Array
,然后在浏览器中基于 UTF-8 编码的字符串计算校验和。 - 如果该库只接受字符串并基于
str.charCodeAt()
计算数据,在 Node.js 端,使用Buffer.from(str, 'utf16le')
将字符串转换为缓冲区。
import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';
let crc = zlib.crc32('hello'); // 907060870
crc = zlib.crc32('world', crc); // 4192936109
crc = zlib.crc32(Buffer.from('hello', 'utf16le')); // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc); // 4150509955
const zlib = require('node:zlib');
const { Buffer } = require('node:buffer');
let crc = zlib.crc32('hello'); // 907060870
crc = zlib.crc32('world', crc); // 4192936109
crc = zlib.crc32(Buffer.from('hello', 'utf16le')); // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc); // 4150509955
zlib.createBrotliCompress([options])
#
options
<brotli options>
创建并返回一个新的 BrotliCompress
对象。
zlib.createBrotliDecompress([options])
#
options
<brotli options>
创建并返回一个新的 BrotliDecompress
对象。
zlib.createDeflate([options])
#
options
<zlib options>
创建并返回一个新的 Deflate
对象。
zlib.createDeflateRaw([options])
#
options
<zlib options>
创建并返回一个新的 DeflateRaw
对象。
zlib 从 1.2.8 升级到 1.2.11 改变了当为原始 deflate 流设置 windowBits
为 8 时的行为。zlib 过去会自动将 windowBits
设置为 9,如果它最初被设置为 8。新版本的 zlib 会抛出异常,因此 Node.js 恢复了将值 8 升级到 9 的原始行为,因为向 zlib 传递 windowBits = 9
实际上会产生一个有效使用 8 位窗口的压缩流。
zlib.createGunzip([options])
#
options
<zlib options>
创建并返回一个新的 Gunzip
对象。
zlib.createGzip([options])
#
options
<zlib options>
zlib.createInflate([options])
#
options
<zlib options>
创建并返回一个新的 Inflate
对象。
zlib.createInflateRaw([options])
#
options
<zlib options>
创建并返回一个新的 InflateRaw
对象。
zlib.createUnzip([options])
#
options
<zlib options>
创建并返回一个新的 Unzip
对象。
zlib.createZstdCompress([options])
#
options
<zstd options>
创建并返回一个新的 ZstdCompress
对象。
zlib.createZstdDecompress([options])
#
options
<zstd options>
创建并返回一个新的 ZstdDecompress
对象。
便捷方法#
所有这些方法都接受 <Buffer>、<TypedArray>、<DataView>、<ArrayBuffer> 或字符串作为第一个参数,一个可选的第二个参数来为 zlib
类提供选项,并将使用 callback(error, result)
调用提供的回调函数。
每个方法都有一个 *Sync
的对应方法,它们接受相同的参数,但没有回调函数。
zlib.brotliCompress(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<brotli options>callback
<Function>
zlib.brotliCompressSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<brotli options>
使用 BrotliCompress
压缩数据块。
zlib.brotliDecompress(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<brotli options>callback
<Function>
zlib.brotliDecompressSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<brotli options>
使用 BrotliDecompress
解压缩数据块。
zlib.deflate(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.deflateSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 Deflate
压缩数据块。
zlib.deflateRaw(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.deflateRawSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 DeflateRaw
压缩数据块。
zlib.gunzip(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.gunzipSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 Gunzip
解压缩数据块。
zlib.gzip(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.gzipSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 Gzip
压缩数据块。
zlib.inflate(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.inflateSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 Inflate
解压缩数据块。
zlib.inflateRaw(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.inflateRawSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 InflateRaw
解压缩数据块。
zlib.unzip(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>callback
<Function>
zlib.unzipSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zlib options>
使用 Unzip
解压缩数据块。
zlib.zstdCompress(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zstd options>callback
<Function>
zlib.zstdCompressSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zstd options>
使用 ZstdCompress
压缩数据块。
zlib.zstdDecompress(buffer[, options], callback)
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zstd options>callback
<Function>
zlib.zstdDecompressSync(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <string>options
<zstd options>
使用 ZstdDecompress
解压缩数据块。