实现说明
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(' '));