From a42629c9ec83a5bf345817cc8132d65c30235dcb Mon Sep 17 00:00:00 2001 From: Murilo Kakazu Date: Sun, 3 Dec 2023 10:49:50 -0300 Subject: [PATCH] fs: use default w flag for writeFileSync with utf8 encoding PR-URL: https://github.com/nodejs/node/pull/50990 Reviewed-By: Luigi Pinca Reviewed-By: Yagiz Nizipli --- lib/fs.js | 6 +++--- test/parallel/test-fs-write-file-sync.js | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index a65bd0274e6f82..a3a9f3386de2b4 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -2341,6 +2341,8 @@ function writeFileSync(path, data, options) { validateBoolean(flush, 'options.flush'); + const flag = options.flag || 'w'; + // C++ fast path for string data and UTF8 encoding if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8')) { if (!isInt32(path)) { @@ -2349,7 +2351,7 @@ function writeFileSync(path, data, options) { return binding.writeFileUtf8( path, data, - stringToFlags(options.flag), + stringToFlags(flag), parseFileMode(options.mode, 'mode', 0o666), ); } @@ -2359,8 +2361,6 @@ function writeFileSync(path, data, options) { data = Buffer.from(data, options.encoding || 'utf8'); } - const flag = options.flag || 'w'; - const isUserFd = isFd(path); // File descriptor ownership const fd = isUserFd ? path : fs.openSync(path, flag, options.mode); diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 26aa819a8107f0..4ead91530bb748 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -101,6 +101,22 @@ tmpdir.refresh(); assert.strictEqual(content, 'hello world!'); } +// Test writeFileSync with no flags +{ + const utf8Data = 'hello world!'; + for (const test of [ + { data: utf8Data }, + { data: utf8Data, options: { encoding: 'utf8' } }, + { data: Buffer.from(utf8Data, 'utf8').toString('hex'), options: { encoding: 'hex' } }, + ]) { + const file = tmpdir.resolve(`testWriteFileSyncNewFile_${Math.random()}.txt`); + fs.writeFileSync(file, test.data, test.options); + + const content = fs.readFileSync(file, { encoding: 'utf-8' }); + assert.strictEqual(content, utf8Data); + } +} + // Test writeFileSync with an invalid input { const file = tmpdir.resolve('testWriteFileSyncInvalid.txt');