Skip to content

Commit

Permalink
fs: use default w flag for writeFileSync with utf8 encoding
Browse files Browse the repository at this point in the history
PR-URL: #50990
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Yagiz Nizipli <[email protected]>
  • Loading branch information
MuriloKakazu authored and UlisesGascon committed Jan 3, 2024
1 parent 2f6d741 commit a42629c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -2349,7 +2351,7 @@ function writeFileSync(path, data, options) {

return binding.writeFileUtf8(
path, data,
stringToFlags(options.flag),
stringToFlags(flag),
parseFileMode(options.mode, 'mode', 0o666),
);
}
Expand All @@ -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);

Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-fs-write-file-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit a42629c

Please sign in to comment.