可迭代压缩


🌐 Iterable Compression

稳定性: 1 - 实验性

源代码: lib/zlib/iter.js

node:zlib/iter 模块提供压缩和解压缩转换,可用于 node:stream/iter 可迭代流 API。

🌐 The node:zlib/iter module provides compression and decompression transforms for use with the node:stream/iter iterable streams API.

此模块仅在启用 --experimental-stream-iter CLI 标志时可用。

🌐 This module is available only when the --experimental-stream-iter CLI flag is enabled.

每个算法都有一个异步版本(有状态异步生成器,用于 pull()pipeTo())以及一个同步版本(有状态同步生成器,用于 pullSync()pipeToSync())。

🌐 Each algorithm has both an async variant (stateful async generator, for use with pull() and pipeTo()) and a sync variant (stateful sync generator, for use with pullSync() and pipeToSync()).

异步转换在 libuv 线程池上运行压缩,将 I/O 与 JavaScript 执行重叠。同步转换直接在主线程上运行压缩。

🌐 The async transforms run compression on the libuv threadpool, overlapping I/O with JavaScript execution. The sync transforms run compression directly on the main thread.

注意:这些转换的默认设置针对流式传输吞吐量进行了优化, 并且与 node:zlib 中的默认设置不同。特别是,gzip/deflate 的默认级别为 4(而不是 6),内存级别为 9(而不是 8),而 Brotli 默认质量为 6(而不是 11)。这些选择符合常见的 HTTP 服务器配置,并在仅略微降低压缩率的情况下提供显著更快的压缩速度。所有默认设置都可以通过选项进行覆盖。

import { from, pull, bytes, text } from 'node:stream/iter';
import { compressGzip, decompressGzip } from 'node:zlib/iter';

// Async round-trip
const compressed = await bytes(pull(from('hello'), compressGzip()));
const original = await text(pull(from(compressed), decompressGzip()));
console.log(original); // 'hello'const { from, pull, bytes, text } = require('node:stream/iter');
const { compressGzip, decompressGzip } = require('node:zlib/iter');

async function run() {
  const compressed = await bytes(pull(from('hello'), compressGzip()));
  const original = await text(pull(from(compressed), decompressGzip()));
  console.log(original); // 'hello'
}

run().catch(console.error);
import { fromSync, pullSync, textSync } from 'node:stream/iter';
import { compressGzipSync, decompressGzipSync } from 'node:zlib/iter';

// Sync round-trip
const compressed = pullSync(fromSync('hello'), compressGzipSync());
const original = textSync(pullSync(compressed, decompressGzipSync()));
console.log(original); // 'hello'const { fromSync, pullSync, textSync } = require('node:stream/iter');
const { compressGzipSync, decompressGzipSync } = require('node:zlib/iter');

const compressed = pullSync(fromSync('hello'), compressGzipSync());
const original = textSync(pullSync(compressed, decompressGzipSync()));
console.log(original); // 'hello'