Node.js

Cancel a pending file read with AbortController

ReadFile accepts an AbortSignal so a caller can stop waiting for an unneeded read. Handle cancellation distinctly from ordinary filesystem errors when your workflow needs a clear reason for stopping.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {readFile} from "node:fs/promises";
const controller = new AbortController();
controller.abort();
try {
  await readFile(new URL(import.meta.url), {encoding: "utf8", signal: controller.signal});
} catch (error) { console.log(error.name); }

How it works

The example aborts before starting, making the rejection reproducible without a huge fixture or timing race. For real work, retain the controller while the read is pending and abort it when the caller cancels or the operation becomes irrelevant.

Limits and mistakes

Aborting readFile does not promise cancellation of every operating-system request already in flight. Do not use this API as a guarantee that no disk activity occurred. A pre-aborted signal also cannot be reset for a later operation.

Check the result

Expect AbortError. Use a new controller for a second read and confirm normal reading still works. Keep cancellation handling separate from missing-file handling.

Sources

Reference documentation for the behavior used in this guide: