Skip to content

Commit f828fa8

Browse files
Nitzan UzielyLinkgoron
Nitzan Uziely
authored andcommitted
fs: fix pre-aborted writeFile AbortSignal file leak
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.
1 parent 04fb597 commit f828fa8

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

lib/internal/fs/promises.js

+16-2
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ const {
6666
const { opendir } = require('internal/fs/dir');
6767
const {
6868
parseFileMode,
69+
validateAbortSignal,
6970
validateBoolean,
7071
validateBuffer,
7172
validateInteger,
@@ -668,14 +669,23 @@ async function writeFile(path, data, options) {
668669
data = Buffer.from(data, options.encoding || 'utf8');
669670
}
670671

672+
validateAbortSignal(options.signal);
671673
if (path instanceof FileHandle)
672674
return writeFileHandle(path, data, options.signal);
673675

674-
const fd = await open(path, flag, options.mode);
675676
if (options.signal?.aborted) {
676677
throw lazyDOMException('The operation was aborted', 'AbortError');
677678
}
678-
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
679+
680+
const fd = await open(path, flag, options.mode);
681+
try {
682+
if (options.signal?.aborted) {
683+
throw lazyDOMException('The operation was aborted', 'AbortError');
684+
}
685+
await writeFileHandle(fd, data);
686+
} finally {
687+
await fd.close();
688+
}
679689
}
680690

681691
async function appendFile(path, data, options) {
@@ -692,6 +702,10 @@ async function readFile(path, options) {
692702
if (path instanceof FileHandle)
693703
return readFileHandle(path, options);
694704

705+
if (options.signal?.aborted) {
706+
throw lazyDOMException('The operation was aborted', 'AbortError');
707+
}
708+
695709
const fd = await open(path, flag, 0o666);
696710
return PromisePrototypeFinally(readFileHandle(fd, options), fd.close);
697711
}

0 commit comments

Comments
 (0)