# Node.js 压缩大文件不想整份读进内存，怎样等管道写完再报成功？

**URL:** <https://www.shiqidu.com/t/topic/2136>\
**Category:** 开发调优\
**Tags:** JavaScript, 编程, 开源软件, Node.js\
**Created:** [2026 年11 月 18 日 07:14 UTC](https://www.shiqidu.com/t/topic/2136 "2026-11-18T07:14:07Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![shiqidu\_editor](https://www.shiqidu.com/user_avatar/www.shiqidu.com/shiqidu_editor/32/528_2.png) [@shiqidu\_editor](https://www.shiqidu.com/u/shiqidu_editor)\
发布日期： [2026 年11 月 18 日 07:14 UTC](https://www.shiqidu.com/t/topic/2136/1 "2026-11-18T07:14:07Z")

</div>

把整个文件 `readFile` 进内存再压缩，大文件会先占掉一份完整缓冲。成功日志的时机也容易弄错，比如异步调用刚发出去就打印「压缩成功」，或者只监听源流的 `end`、压缩变换可写端的 `finish`。源流的 `end` 只表示读入结束，压缩和写入可能还在进行。压缩变换可写端的 `finish` 也不等于目标文件已经写完。只听这类单个事件，还接不住整条链上的错误。磁盘上已经出现一个 `.gz`，甚至体积变小了，都还不能说明内容完整，也不能说明管道已经走完。

[zlib 文档](https://nodejs.org/api/zlib.html) 把本地文件压缩写成三条流：`createReadStream` 读源文件，`createGzip` 做变换，`createWriteStream` 写目标。[stream 文档](https://nodejs.org/api/stream.html) 的 Streams Promises API 里，`pipeline` 返回的 Promise 会在管道完成时兑现。回调版说明里也写了，它会转发错误，结束时做清理，并在管道完成时给出结果。把成功日志放在 `await` 之后，异常在外层捕获，并把 `process.exitCode` 设成非零。输入和输出路径从命令行传入，这样每次都可以换一条新的、可丢弃的输出路径：

```javascript
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';

const inputPath = process.argv[2];
const outputPath = process.argv[3];

if (!inputPath || !outputPath) {
  console.error('用法: node gzip-file.mjs <输入文件> <输出.gz>');
  process.exitCode = 1;
} else {
  try {
    await pipeline(
      createReadStream(inputPath),
      createGzip(),
      createWriteStream(outputPath),
    );
    console.log('压缩完成');
  } catch (err) {
    console.error('压缩失败', err.code);
    process.exitCode = 1;
  }
}

```

调用时写成 `node gzip-file.mjs ./sample.bin ./sample.bin.gz`。这里的「压缩完成」只表示这条管道已经跑完。它不表示目标文件是原子替换出来的，也不表示数据已经 `fsync` 到磁盘，更不能保证掉电后一定完整。`createWriteStream` 如果指向一个已经存在的文件，会把原内容覆盖掉。本机用一个已有文件试过，旧内容不再保留。即使这次管道后来成功了，原来那份文件也已经没了，所以不要把输出指到还想留着的旧路径上。

失败时更要小心。`pipeline` 开始组装时就会打开写入端，源文件不存在，输出路径上也可能已经留下空文件或残片。用缺失的输入路径试过：`node gzip-file.mjs ./no-such.bin ./tmp-out.gz` 的退出码是 1，标准输出没有「压缩完成」，标准错误是 `压缩失败 ENOENT`，同时 `./tmp-out.gz` 上多出一个 0 字节文件。输出目录不存在时，例如 `node gzip-file.mjs ./sample.bin ./no-such-dir/out.gz`，同样是非零退出和 `ENOENT`，没有成功消息。这些残片都该丢掉，不要当成压缩结果接着用。

流与流之间会按消费速度协调数据，源端不会无限制地往目标端堆。文档把 `highWaterMark` 写成阈值：内部缓冲达到阈值后，会通过背压让上游暂停送入，等下游继续消费。它不是整个进程的内存上限。这次没有改这个选项，也不要从一次本地示例里外推占用或速度数字。

验收不要看文件在不在、体积小了没有。把 `.gz` 再经过 `createGunzip` 流式解压，和原文件分别算 SHA-256，对得上才算内容一致：

```javascript
import { createReadStream } from 'node:fs';
import { createGunzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
import { createHash } from 'node:crypto';
import { Writable } from 'node:stream';

async function sha256(stream, unzip = false) {
  const hash = createHash('sha256');
  const sink = new Writable({
    write(chunk, _enc, done) {
      hash.update(chunk);
      done();
    },
  });
  if (unzip) {
    await pipeline(stream, createGunzip(), sink);
  } else {
    await pipeline(stream, sink);
  }
  return hash.digest('hex');
}

const src = process.argv[2];
const gz = process.argv[3];
const a = await sha256(createReadStream(src));
const b = await sha256(createReadStream(gz), true);
if (a !== b) {
  console.error('SHA-256 mismatch');
  process.exitCode = 1;
} else {
  console.log('SHA-256 match', a);
}

```

用法是 `node gunzip-sha256.mjs ./sample.bin ./sample.bin.gz`。示例输入用本地合成文件即可，不要拿业务数据去试覆盖和残片。本机跑过后，解压摘要和原文件一致。成功消息只出现在标准输出，失败信息走标准错误，检查时不要只看有没有 `.gz` 文件。两条失败命令的退出码和残片情况见上面。失败之后不要复用那条可能留下残片的输出路径，换一条新的再试。压缩这条链本身没有先把源文件读成一整块再送进 `createGzip`。

这些命令是在 Node.js v24.22.1 上跑的。打开的 zlib 和 stream 文档，标题里写的是滚动文档自己标的版本，不是这次实跑的版本，也不能当成功能的最低支持版本。
