实现说明
异步边界用 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 });