Skip to content

Commit

Permalink
fs: fix pre-aborted writeFile AbortSignal file leak
Browse files Browse the repository at this point in the history
Fix an issue in writeFile where a file is opened, and not closed
if the abort signal is aborted after the file was opened
but before writing began.

PR-URL: #37393
Backport-PR-URL: #38386
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
  • Loading branch information
Nitzan Uziely authored and targos committed Apr 30, 2021
1 parent 7aa2e5d commit 0269413
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const {
const { opendir } = require('internal/fs/dir');
const {
parseFileMode,
validateAbortSignal,
validateBuffer,
validateInteger,
validateUint32
Expand Down Expand Up @@ -646,14 +647,17 @@ async function writeFile(path, data, options) {
data = Buffer.from(data, options.encoding || 'utf8');
}

validateAbortSignal(options.signal);
if (path instanceof FileHandle)
return writeFileHandle(path, data, options.signal);

const fd = await open(path, flag, options.mode);
if (options.signal?.aborted) {
throw new lazyDOMException('The operation was aborted', 'AbortError');
}
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);

const fd = await open(path, flag, options.mode);
const { signal } = options;
return PromisePrototypeFinally(writeFileHandle(fd, data, signal), fd.close);
}

async function appendFile(path, data, options) {
Expand All @@ -670,6 +674,10 @@ async function readFile(path, options) {
if (path instanceof FileHandle)
return readFileHandle(path, options);

if (options.signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}

const fd = await open(path, flag, 0o666);
return PromisePrototypeFinally(readFileHandle(fd, options), fd.close);
}
Expand Down

0 comments on commit 0269413

Please sign in to comment.