使用 pipeline 与 finished 组合,如何处理中间流抛出的错误并自动清理?
解读
国内一线/二线厂面试中,这道题考察的是“流式编程”与“资源安全”两大硬核能力。
- 场景:日志采集、大文件上传、图片转码、音视频切片等 I/O 密集链路,中间任意环节(解压、解密、限流、转码)都可能抛错。
- 痛点:若只 catch 错误而不清理,会出现 fd 泄漏、临时文件残留、内存暴涨,直接触发线上告警。
- 考点:
- 是否理解 pipeline 的“自动传播错误+自动销毁”语义;
- 是否知道 finished 的“资源关闭”语义;
- 能否在 async/await 结构里把两者串成“可回溯、可重试、可观测”的代码;
- 是否熟悉 Node.js 14+ 之后 promisify 工具集的官方最佳实践。
知识点
- stream.pipeline(source, ...transforms, destination, callback)
- 内部已注册 error & close 监听器,任何一环触发 error,会:
– 销毁所有上游流(destroy(err));
– 把错误交给 callback,不再二次触发。
- 内部已注册 error & close 监听器,任何一环触发 error,会:
- stream.finished(stream, opts, callback)
- 监听 'finish'/'end'/'error'/'close',保证在流“完全结束”后调用 callback;
- 可传入 { cleanup: true }(Node.js 18+)自动移除监听器,防止泄漏。
- 错误分类
- 可恢复:限流超限、网络抖动,可重试;
- 不可恢复:文件格式损坏、签名失败,需快速失败并回滚。
- 清理范围
- 文件句柄、临时目录、GPU 显存、分布式锁、消息队列 offset。
- 代码组织
- 用 async/await 包装,外层 try/catch 统一收口;
- 内部用 Promise.allSettled 并行清理,保证“无论成功失败,都要清”;
- 记录 opentracing span,方便 SLS/ELK 回溯。
答案
import { pipeline } from 'node:stream/promises';
import { finished } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { mkdir, rm } from 'node:fs/promises';
/**
* 安全压缩:中间任何一步抛错都会自动销毁所有流,并清理临时目录
* @param {string} src 源文件
* @param {string} dst 目标文件
*/
async function safeCompress(src, dst) {
const tmp = join(tmpdir(), `node-${process.pid}-${Date.now()}`);
await mkdir(tmp, { recursive: true });
const input = createReadStream(src);
const gzip = createGzip();
const output = createWriteStream(dst);
// 关键 1:pipeline 已内置错误传播与销毁
try {
await pipeline(input, gzip, output);
// 关键 2:finished 保证文件落盘再返回
await finished(output, { cleanup: true });
} catch (err) {
// 关键 3:无论哪一步出错,统一清理
await rm(tmp, { recursive: true, force: true }).catch(() => {});
throw Object.assign(err, { cleaned: true });
}
}
/* 使用示例 */
try {
await safeCompress('./big.log', './big.log.gz');
console.log('压缩成功');
} catch (e) {
if (e.cleaned) {
console.error('压缩失败,已自动清理', e.code);
} else {
console.error('未知错误', e);
}
}
要点提炼
- 用 node:stream/promises 的 pipeline,天然“错误传播+自动销毁”,无需手写 destroy。
- finished 等待文件真正落盘,防止“回调已回但数据还在 OS 缓存”的假成功。
- 清理逻辑放在 catch 里,并加 .catch(() => {}) 防止二次抛错把主错误覆盖。
- 返回的 err 上打 cleaned 标记,方便上游决策是否重试。
拓展思考
- 多副本并行
若业务需要“同一份源文件同时压缩+加密+上传三副本”,可用 Promise.allSettled 包三个 pipeline,错误时并行清理所有副本,并回滚分布式事务。 - 背压与限流
在 transform 环节加入 throttle 流(基于 node-rate-limit-transformer),当内存使用 > 75% 时主动 pause(),防止 V8 heap 暴涨导致容器 OOMKilled。 - 日志与告警
把 pipeline 的每一步耗时通过 finished 的回调打到 SLS,设置告警规则:单步耗时 > 5s 或错误率 > 1% 即@值班群,实现“可观测性左移”。 - 升级至 Node.js 20
20.x 的 pipeline 支持 signal 选项,可传入 AbortController,实现“接口超时 30s 自动取消”,比手动 destroy 更优雅。