← 中文资源

简体中文版本

可中止的 fs/promises 读取

把调用方的 AbortSignal 传进 fs/promises 选项:已中止的读取立即以 AbortError 拒绝、不触碰文件;未中止时同一参数照常读取。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

already-aborted read rejected: AbortError
content: {"theme":"dark"}

实现说明

异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。导入清单标出了平台接触面:mkdtemp、readFile、writeFile、rm、tmpdir,全部来自 node:fs/promises、node:os、node:path。 演示用的数据放在这几个模块级绑定中:dir、config、caller。

使用要点

  • 依赖面只有 node:fs/promises,而它内置于 Node.js。
  • 演示输出是带标签的(already-aborted read rejected:、content:),每个操作都会留下自己的一行标注。

常见问题

导入的模块是 npm 包吗?

不需要——node:fs/promises 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。

核心语句

const dir = await mkdtemp(join(tmpdir(), 'abort-fs-'));
await readFile(config, { signal: caller.signal });
await rm(dir, { recursive: true, force: true });

代码示例

import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const dir = await mkdtemp(join(tmpdir(), 'abort-fs-'));
const config = join(dir, 'settings.json');
await writeFile(config, '{"theme":"dark"}');

// The caller already gave up: pass its AbortSignal through the options bag
const caller = new AbortController();
caller.abort();

try {
  await readFile(config, { signal: caller.signal });
} catch (err) {
  console.log('already-aborted read rejected:', err.name);
}

// Un-aborted reads flow through the same options bag
console.log('content:', await readFile(config, 'utf8'));

await rm(dir, { recursive: true, force: true });