Skip to content

fs: support abortsignal in writeFile

Now that https://github.com/nodejs/node/pull/35911 is landed the next suggestion in https://github.com/nodejs/node/pull/35877 by @mcollina was fs.writeFile (here https://github.com/nodejs/node/pull/35877#issuecomment-720071726 ) - so I am going over the suggestions one by one and adding AbortSignal support.

This PR lets you abort an ongoing writeFile request.

const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
(async () => {
  try {
    await fs.writeFile('message.txt', data, { signal });
  } catch (err) {
  // When a request is aborted - err is an AbortError
  }
})();
// When the request should be aborted
controller.abort();

Note that unlike readFile this is very stateful - so some of the data will be written to the file (this is expected IMO). I vaguely recall in the summit @addaleax has something smart to say regarding the error but I don't remember the conclusion. I am happy to tack the offset (how many bytes were written) on the AbortError if that would help.

Merge request reports

Loading