From 758d27ad389690a954d58ebd7e9e3999aeef2bce 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. --- lib/internal/fs/promises.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 6c39a13349d27b..8ffc92ff45c909 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -66,6 +66,7 @@ const { const { opendir } = require('internal/fs/dir'); const { parseFileMode, + validateAbortSignal, validateBoolean, validateBuffer, validateInteger, @@ -668,11 +669,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); + if (options.signal?.aborted) { + throw lazyDOMException('The operation was aborted', 'AbortError'); + } + const fd = await open(path, flag, options.mode); if (options.signal?.aborted) { + await fd.close(); throw lazyDOMException('The operation was aborted', 'AbortError'); } return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close); @@ -692,6 +699,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); }