Node.js 流式计算文件 SHA-256:错误传播、取消与 CLI 测试

10-20 4阅读

给安装包、备份或构建产物计算 SHA-256,并不需要先把整个文件放进内存。真正容易漏掉的是另外几件事:读到一半出错怎么办,用户取消时怎样停止读取,失败时会不会误输出一个“部分文件的摘要”。这篇教程用 Node.js 内置模块做一个可复用函数和命令行工具,把这些行为一起测试。

Node.js 流式计算文件 SHA-256:错误传播、取消与 CLI 测试
独立模型生成的概念示意图,并非真实软件截图。数据块表示增量处理,停止按钮表示取消操作。

一、先约定结果和边界

本文代码采用 .mjs 文件,不需要安装 npm 依赖。实际验证环境为 Linux、Node.js v24.19.0,测试日期为 2026 年 10 月 20 日;其他版本和操作系统没有在本文中实测,不能把这里的测试结果当作跨平台保证。

  • 成功:返回整个文件原始字节的 SHA-256 十六进制字符串,共 64 个字符。

  • 失败:Promise 拒绝,保留可识别的错误信息,不返回部分摘要。

  • 取消:接受 AbortSignal,由流管道终止本次读取。

  • 内存:实现中不使用 readFile、Buffer.concat,也不把所有数据块存进数组。

用途也要分清:摘要适合检查内容是否与某个预期摘要匹配,但摘要本身不能证明文件来自可信发布者。如果文件和摘要都来自同一个被篡改的渠道,比对成功并不等于安全。普通 SHA-256 也不是密码存储方案,不能把本工具改成“给密码做一次 SHA-256”就当作合格的密码保护。

二、用 pipeline 管理读取、错误和取消

新建 sha256-file.mjs:

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

// readable should emit bytes, not decoded text or arbitrary objects.
export async function sha256Stream(readable, { signal } = {}) {
  const hash = createHash('sha256');
  const sink = new Writable({
    write(chunk, encoding, callback) {
      try {
        hash.update(chunk);
        callback();
      } catch (error) {
        callback(error);
      }
    },
  });

  await pipeline(readable, sink, { signal });
  // Only return a digest after the entire pipeline succeeds.
  return hash.digest('hex');
}

export async function sha256File(path, { signal } = {}) {
  const input = createReadStream(path, {
    highWaterMark: 64 * 1024,
  });
  return sha256Stream(input, { signal });
}

这里把“读取文件”和“处理字节流”分开。sha256File 只负责创建文件流,sha256Stream 则负责按顺序消费数据。因此测试既能访问真实文件,也能注入一个故意报错的流,不必依赖难以复现的磁盘故障。

每收到一个块,Writable 调用一次 hash.update;只有 await pipeline 成功完成,代码才会执行 hash.digest。digest 不能在每个块后调用,也不能在 catch 中调用来“保留进度”。Node.js 官方文档明确说明,update 可以多次执行,digest 之后该 Hash 对象不能再继续使用。参见 hash.update 和 hash.digest。

为什么不用 input.pipe(sink) 后直接返回?因为还需要可靠地等待完成、接收错误并处理取消。这里使用 Promise 版 pipeline,把这些结果统一汇入 await。官方说明将 signal 放在最后一个 options 参数中,取消后会销毁管道并产生 AbortError。参见 Streams Promises API。

write 内的 try/catch 不是吞掉异常,而是通过 callback(error) 交还给流机制。正常路径同样需要调用 callback,告诉 Writable 这一块已处理完。当前实现中的 hash.update 是同步调用,取消信号不能强行打断正在执行的这一小段同步运算。

三、“64 KiB 分块”不等于进程只占 64 KiB

createReadStream 没有设置文本 encoding,所以文件按原始字节读取。不要先转成 UTF-8 文本再计算二进制文件摘要:解码、换行处理或重新编码都可能改变待计算的字节。

代码显式设置 64 × 1024 的 highWaterMark,是为了给示例一个容易理解的读取缓冲阈值,而不是宣称进程内存上限为 64 KiB。运行时、流缓冲、哈希内部状态以及操作系统缓存都可能占用额外内存。这里能直接检查的事实是:应用没有累计保存整个文件,哈希状态随数据块持续更新。

文件流默认负责关闭文件描述符,本例没有把 autoClose 改为 false。参数语义可查 fs.createReadStream 官方说明。另外,本工具不锁定文件,也不创建一致性快照。如果另一个进程正在修改文件,所得摘要代表实际读到的字节,不保证对应某一时刻完整的文件版本。应先冻结产物或对稳定副本计算摘要。

四、加上可取消、可超时的命令行入口

将下面内容保存为同目录的 hash-cli.mjs。它只把成功的摘要写入标准输出;提示、失败和取消信息走标准错误,方便脚本区分结果。

import { sha256File } from './sha256-file.mjs';

const usage = 'Usage: node hash-cli.mjs <file> [--timeout-ms N]';

async function main(args) {
  if (args.length === 1 && args[0] === '--help') {
    console.log(usage);
    return 0;
  }
  const [file, option, rawTimeout] = args;
  const timeoutMs = rawTimeout === undefined ? undefined : Number(rawTimeout);
  const validTimeout = /^\d+$/.test(rawTimeout ?? '') &&
    Number.isSafeInteger(timeoutMs) &&
    timeoutMs >= 1 && timeoutMs <= 2_147_483_647;
  if (!file || !([1, 3].includes(args.length)) ||
      (args.length === 3 && (option !== '--timeout-ms' || !validTimeout))) {
    console.error(usage);
    return 2;
  }

  const controller = new AbortController();
  let cancelledBy;
  const cancel = (reason) => {
    if (!controller.signal.aborted) {
      cancelledBy = reason;
      controller.abort();
    }
  };
  const onSigint = () => cancel('SIGINT');
  process.on('SIGINT', onSigint);
  const timer = timeoutMs === undefined
    ? undefined
    : setTimeout(() => cancel('timeout'), timeoutMs);

  try {
    const digest = await sha256File(file, { signal: controller.signal });
    console.log(digest);
    return 0;
  } catch (error) {
    if (error.code === 'ABORT_ERR') {
      console.error(cancelledBy === 'timeout' ? 'Hash timed out.' : 'Hash cancelled.');
      return cancelledBy === 'timeout' ? 124 : 130;
    }
    console.error(`${error.code ?? error.name}: ${error.message}`);
    return 1;
  } finally {
    clearTimeout(timer);
    process.off('SIGINT', onSigint);
  }
}

process.exitCode = await main(process.argv.slice(2));

下面是终端命令,不是 JavaScript。先创建恰好包含三个字节 abc、没有换行的文件,再运行工具:

node -e "require('node:fs').writeFileSync('sample.txt', 'abc')"
node hash-cli.mjs sample.txt
node hash-cli.mjs "a file with spaces.bin" --timeout-ms 10000

第一条计算命令的预期输出为:

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

不要用一个会自动附加换行的命令生成测试输入,再拿 abc 的摘要来判断实现是否正确。多出来的换行本身就是文件内容的一部分。

这个示例约定的退出码是:0 表示成功,1 表示读取等运行错误,2 表示参数错误,124 表示超时,130 表示收到 Ctrl+C 对应的 SIGINT 后取消。124 和 130 是本工具选择的接口约定,不是 sha256File 的返回值。

超时值限制为 1 到 2147483647 的十进制整数。定时器不是精确实时中断:事件循环忙碌时,取消回调可能晚于指定时间执行。无论成功还是失败,finally 都会清理定时器和 SIGINT 监听器,避免留下与本次操作无关的行为。

五、测试不要只验证一个正常文件

将下面内容保存为 sha256-file.test.mjs。测试使用内置 node:test 与 node:assert/strict,临时目录在测试完成后清理。二进制样本由 513 个 4097 字节的数据块组成,跨越多个文件流读取边界;构建样本时也没有拼出一个完整的大 Buffer。

import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { sha256File, sha256Stream } from './sha256-file.mjs';

const abcHash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
const emptyHash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
const cli = fileURLToPath(new URL('./hash-cli.mjs', import.meta.url));
const runCli = (...args) => spawnSync(process.execPath, [cli, ...args], {
  encoding: 'utf8', timeout: 10_000,
});

async function temp(t) {
  const dir = await mkdtemp(join(tmpdir(), 'stream-hash-'));
  t.after(() => rm(dir, { recursive: true, force: true }));
  return dir;
}

test('abc and empty file match known SHA-256 vectors', async (t) => {
  const dir = await temp(t);
  const file = join(dir, 'sample.bin');
  await writeFile(file, 'abc');
  assert.equal(await sha256File(file), abcHash);
  await writeFile(file, '');
  assert.equal(await sha256File(file), emptyHash);
});

test('binary input crosses many read boundaries', async (t) => {
  const dir = await temp(t);
  const file = join(dir, 'binary.bin');
  const expected = createHash('sha256');
  function* chunks() {
    for (let n = 0; n < 513; n++) {
      const chunk = Buffer.alloc(4097, n % 256);
      expected.update(chunk);
      yield chunk;
    }
  }
  await pipeline(Readable.from(chunks()), createWriteStream(file));
  assert.equal(await sha256File(file), expected.digest('hex'));
});

test('missing file rejects with ENOENT', async (t) => {
  const dir = await temp(t);
  await assert.rejects(sha256File(join(dir, 'missing')), { code: 'ENOENT' });
});

test('upstream read error is preserved', async () => {
  const failure = Object.assign(new Error('simulated read failure'), { code: 'EIO' });
  const input = new Readable({ read() { this.destroy(failure); } });
  await assert.rejects(sha256Stream(input), (error) => error === failure);
  assert.equal(input.destroyed, true);
});

test('premature close cannot produce a partial digest', async () => {
  const input = new Readable({ read() { this.push(Buffer.from('part')); this.destroy(); } });
  await assert.rejects(sha256Stream(input), { code: 'ERR_STREAM_PREMATURE_CLOSE' });
});

test('already aborted signal rejects', async (t) => {
  const dir = await temp(t);
  const file = join(dir, 'sample');
  await writeFile(file, 'abc');
  const controller = new AbortController();
  controller.abort();
  await assert.rejects(sha256File(file, { signal: controller.signal }), {
    name: 'AbortError', code: 'ABORT_ERR',
  });
});

test('mid-stream abort rejects and destroys input', { timeout: 2000 }, async () => {
  const controller = new AbortController();
  let started = false;
  const input = new Readable({
    read() {
      if (started) return;
      started = true;
      this.push(Buffer.from('partial bytes'));
      // Keep the stream open until cancellation, without a timing race with EOF.
      setImmediate(() => controller.abort());
    },
  });
  await assert.rejects(sha256Stream(input, { signal: controller.signal }), {
    name: 'AbortError', code: 'ABORT_ERR',
  });
  assert.equal(started, true);
  assert.equal(input.destroyed, true);
});

test('CLI success prints only the digest', async (t) => {
  const dir = await temp(t);
  const file = join(dir, 'a file with spaces');
  await writeFile(file, 'abc');
  const result = runCli(file, '--timeout-ms', '10000');
  assert.equal(result.error, undefined);
  assert.equal(result.status, 0);
  assert.equal(result.stdout.trim(), abcHash);
  assert.equal(result.stderr, '');
});

test('CLI file error does not print a digest', async (t) => {
  const dir = await temp(t);
  const result = runCli(join(dir, 'missing'));
  assert.equal(result.status, 1);
  assert.equal(result.stdout, '');
  assert.match(result.stderr, /ENOENT/);
});

test('CLI rejects missing args, unknown flag and invalid timeout', () => {
  for (const args of [[], ['x', '--bad', '5'], ['x', '--timeout-ms', '0'],
    ['x', '--timeout-ms', '2147483648'], ['x', '--timeout-ms', 'NaN']]) {
    const result = runCli(...args);
    assert.equal(result.status, 2);
    assert.equal(result.stdout, '');
    assert.match(result.stderr, /Usage:/);
  }
});

运行以下终端命令:

node --test sha256-file.test.mjs

这组测试在上述实测环境中得到 10 项通过、0 项失败、0 项跳过。运行器使用方式参见 Node.js test runner 文档。

  • 固定的 abc 和空文件摘要,避免把明显错误的输入处理误当成成功。

  • 跨读取边界的二进制文件,检查数据没有被错误转换或丢块。测试中的逐块摘要对照仍使用同一套 crypto 实现,这是集成验证,不是对 SHA-256 算法的独立数学证明。

  • ENOENT、模拟 EIO 以及提前关闭,确认错误不会变成成功结果。

  • 开始前已经取消,以及读到一部分后取消,确认 Promise 拒绝,输入流被销毁。

  • CLI 正常输出、文件错误和非法参数,确认退出码及标准输出/标准错误符合约定。

处理中取消的测试故意让输入流保持未结束状态,再触发 abort,不用“文件一定会比定时器读得慢”这种不稳定假设。此外,在 Linux 上还对持续输出值为 0 的字节的 /dev/zero 做了两个命令行集成检查:超时返回 124,确认输入已打开后发送 SIGINT 返回 130,两者标准输出均为空。这两个检查不是跨平台测试,也不属于上面 10 个测试用例的数量。

六、接入业务时保留这些限制

  • 错误后重新执行时,重新创建文件流与 Hash 对象,不复用已失败或已结束的实例。

  • 一次只处理一个文件最容易控制资源。批量任务可加有限并发,但不要无上限地同时打开大量文件。

  • 流式 I/O 不等于哈希计算全部离开主线程。对延迟敏感的服务,应结合真实负载决定是否把计算交给独立工作进程或线程;本文没有做吞吐量或延迟基准测试。

  • 如果后续要根据摘要决定是否执行下载的软件,可信的预期摘要或签名验证渠道仍然必不可少。

这个实现的重点不是把代码压缩成一行,而是明确承诺:只在完整读取成功后交付摘要;读取失败就失败,取消就取消。这样一个小工具,才适合继续放进构建、备份与文件校验流程。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。