From b378fc3ac08f2102eb3107254dd4591dbe3940bb Mon Sep 17 00:00:00 2001 From: Livia Medeiros Date: Sun, 6 Jul 2025 13:32:45 +0800 Subject: [PATCH] fs: close dir before throwing if `options.bufferSize` is invalid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/58856 Fixes: https://github.com/nodejs/node/issues/58854 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Juan José Arboleda --- lib/internal/fs/dir.js | 8 +++++++- test/parallel/test-fs-opendir.js | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/internal/fs/dir.js b/lib/internal/fs/dir.js index 1fa75018486..88b797ca905 100644 --- a/lib/internal/fs/dir.js +++ b/lib/internal/fs/dir.js @@ -59,7 +59,13 @@ class Dir { }), }; - validateUint32(this.#options.bufferSize, 'options.bufferSize', true); + try { + validateUint32(this.#options.bufferSize, 'options.bufferSize', true); + } catch (validationError) { + // Userland won't be able to close handle if we throw, so we close it first + this.#handle.close(); + throw validationError; + } this.#readPromisified = FunctionPrototypeBind( promisify(this.#readImpl), this, false); diff --git a/test/parallel/test-fs-opendir.js b/test/parallel/test-fs-opendir.js index 620ca20aae2..5e3a92dab42 100644 --- a/test/parallel/test-fs-opendir.js +++ b/test/parallel/test-fs-opendir.js @@ -4,12 +4,20 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); +const process = require('node:process'); const tmpdir = require('../common/tmpdir'); const testDir = tmpdir.path; const files = ['empty', 'files', 'for', 'just', 'testing']; +process.on('warning', (cause) => { + // If any directory handle was left unclosed and then GC'd, + // it will emit `Warning: Closing directory handle on garbage collection`. + // Treat this warning as error. + throw new Error('Expected no warnings', { cause }); +}); + // Make sure tmp directory is clean tmpdir.refresh();