Skip to content

Commit 7245486

Browse files
MuriloKakazutargos
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 b24ee15 commit 7245486

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
@@ -2343,6 +2343,8 @@ function writeFileSync(path, data, options) {
23432343

23442344
validateBoolean(flush, 'options.flush');
23452345

2346+
const flag = options.flag || 'w';
2347+
23462348
// C++ fast path for string data and UTF8 encoding
23472349
if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8')) {
23482350
if (!isInt32(path)) {
@@ -2351,7 +2353,7 @@ function writeFileSync(path, data, options) {
23512353

23522354
return binding.writeFileUtf8(
23532355
path, data,
2354-
stringToFlags(options.flag),
2356+
stringToFlags(flag),
23552357
parseFileMode(options.mode, 'mode', 0o666),
23562358
);
23572359
}
@@ -2361,8 +2363,6 @@ function writeFileSync(path, data, options) {
23612363
data = Buffer.from(data, options.encoding || 'utf8');
23622364
}
23632365

2364-
const flag = options.flag || 'w';
2365-
23662366
const isUserFd = isFd(path); // File descriptor ownership
23672367
const fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
23682368

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)