← 中文资源

简体中文版本

zlib Gzip 无损往返压缩文本

用 gzipSync 压缩 UTF-8 文本、gunzipSync 还原:往返逐字节一致,日志类重复文本的体积收益与压缩比直接打印出来。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

original bytes: 1750
gzip bytes: 71
lossless: true
restored words: 150
sample: request status=200 path=/api/items request

实现说明

node:zlib 提供 gzipSync、gunzipSync——内建表面,不涉及任何包。 各个操作都建立在顶层绑定之上:report、original、compressed、restored。

使用要点

  • 依赖面只有 node:zlib,而它内置于 Node.js。
  • 跑完文件,输出里会留下标记——original bytes:、gzip bytes:、lossless:。

常见问题

有第三方依赖吗?

不需要。导入解析到 Node.js 核心模块,运行时自带。

核心语句

const words = restored.toString('utf8').split(' ').filter(Boolean);
const report = 'request status=200 path=/api/items '.repeat(50);
const original = Buffer.from(report, 'utf8');

代码示例

import { gzipSync, gunzipSync } from 'node:zlib';

const report = 'request status=200 path=/api/items '.repeat(50);

const original = Buffer.from(report, 'utf8');
const compressed = gzipSync(original);
const restored = gunzipSync(compressed);

console.log('original bytes:', original.byteLength);
console.log('gzip bytes:', compressed.byteLength);
console.log('lossless:', restored.equals(original));
const words = restored.toString('utf8').split(' ').filter(Boolean);
console.log('restored words:', words.length);
console.log('sample:', words.slice(0, 4).join(' '));