From 026941381b2a3d49b6d9b3a5e12f3c6e71cf4542 Mon Sep 17 00:00:00 2001 From: Nitzan Uziely Date: Tue, 16 Feb 2021 15:18:51 +0200 Subject: [PATCH] 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. PR-URL: https://github.com/nodejs/node/pull/37393 Backport-PR-URL: https://github.com/nodejs/node/pull/38386 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Antoine du Hamel --- lib/internal/fs/promises.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index a6b50054774f4e..ccac60477ff83c 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -63,6 +63,7 @@ const { const { opendir } = require('internal/fs/dir'); const { parseFileMode, + validateAbortSignal, validateBuffer, validateInteger, validateUint32 @@ -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) { @@ -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); }