Skip to content

Commit 435f9c9

Browse files
MuriloKakazuUlisesGascon
authored andcommitted
fs: use default w flag for writeFileSync with utf8 encoding
PR-URL: #50990 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz.nizipli@sentry.io>
1 parent b2b4132 commit 435f9c9

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lib/fs.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -2341,6 +2341,8 @@ function writeFileSync(path, data, options) {
23412341

23422342
validateBoolean(flush, 'options.flush');
23432343

2344+
const flag = options.flag || 'w';
2345+
23442346
// C++ fast path for string data and UTF8 encoding
23452347
if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8')) {
23462348
if (!isInt32(path)) {
@@ -2349,7 +2351,7 @@ function writeFileSync(path, data, options) {
23492351

23502352
return binding.writeFileUtf8(
23512353
path, data,
2352-
stringToFlags(options.flag),
2354+
stringToFlags(flag),
23532355
parseFileMode(options.mode, 'mode', 0o666),
23542356
);
23552357
}
@@ -2359,8 +2361,6 @@ function writeFileSync(path, data, options) {
23592361
data = Buffer.from(data, options.encoding || 'utf8');
23602362
}
23612363

2362-
const flag = options.flag || 'w';
2363-
23642364
const isUserFd = isFd(path); // File descriptor ownership
23652365
const fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
23662366

test/parallel/test-fs-write-file-sync.js

+16
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,22 @@ tmpdir.refresh();
101101
assert.strictEqual(content, 'hello world!');
102102
}
103103

104+
// Test writeFileSync with no flags
105+
{
106+
const utf8Data = 'hello world!';
107+
for (const test of [
108+
{ data: utf8Data },
109+
{ data: utf8Data, options: { encoding: 'utf8' } },
110+
{ data: Buffer.from(utf8Data, 'utf8').toString('hex'), options: { encoding: 'hex' } },
111+
]) {
112+
const file = tmpdir.resolve(`testWriteFileSyncNewFile_${Math.random()}.txt`);
113+
fs.writeFileSync(file, test.data, test.options);
114+
115+
const content = fs.readFileSync(file, { encoding: 'utf-8' });
116+
assert.strictEqual(content, utf8Data);
117+
}
118+
}
119+
104120
// Test writeFileSync with an invalid input
105121
{
106122
const file = tmpdir.resolve('testWriteFileSyncInvalid.txt');

0 commit comments

Comments
 (0)