Abortable fs/promises Reads With AbortSignal
Pass an AbortSignal into fs/promises options so a caller that already timed out rejects the read immediately without touching the file.
Code
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 });Output
Captured from a sandboxed run of this snippet in the build pipeline.
already-aborted read rejected: AbortError
content: {"theme":"dark"}How the snippet works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import names the platform contact area: mkdtemp, readFile, writeFile, rm, tmpdir, all from node:fs/promises, node:os, node:path.
Top-level bindings dir, config, caller hold the demo state — nothing sits inside a function scope.
What to watch for
- The dependency surface is just
node:fs/promises, and that one is built into Node.js.
Applying it
The run prints already-aborted read rejected:, content: — each prefix names the step that produced it.
Statements that matter
const dir = await mkdtemp(join(tmpdir(), 'abort-fs-'));
await readFile(config, { signal: caller.signal });
await rm(dir, { recursive: true, force: true });
Interactive Tools for This Topic
FAQ
- Is the imported module an npm package?
- No — `node:fs/promises` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.