Skip to content

Commit 7bfb087

Browse files
authored
fs: use default w flag for writeFileSync with utf8 encoding
PR-URL: #50990 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Yagiz Nizipli <[email protected]>
1 parent 23031d9 commit 7bfb087

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

‎lib/fs.js‎

Lines changed: 3 additions & 3 deletions
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+
constflag=options.flag||'w';
2347+
23462348
// C++ fast path for string data and UTF8 encoding
23472349
if(typeofdata==='string'&&(options.encoding==='utf8'||options.encoding==='utf-8')){
23482350
if(!isInt32(path)){
@@ -2351,7 +2353,7 @@ function writeFileSync(path, data, options){
23512353

23522354
returnbinding.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-
constflag=options.flag||'w';
2365-
23662366
constisUserFd=isFd(path);// File descriptor ownership
23672367
constfd=isUserFd ? path : fs.openSync(path,flag,options.mode);
23682368

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

Lines changed: 16 additions & 0 deletions
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+
constutf8Data='hello world!';
107+
for(consttestof[
108+
{data: utf8Data},
109+
{data: utf8Data,options: {encoding: 'utf8'}},
110+
{data: Buffer.from(utf8Data,'utf8').toString('hex'),options: {encoding: 'hex'}},
111+
]){
112+
constfile=tmpdir.resolve(`testWriteFileSyncNewFile_${Math.random()}.txt`);
113+
fs.writeFileSync(file,test.data,test.options);
114+
115+
constcontent=fs.readFileSync(file,{encoding: 'utf-8'});
116+
assert.strictEqual(content,utf8Data);
117+
}
118+
}
119+
104120
// Test writeFileSync with an invalid input
105121
{
106122
constfile=tmpdir.resolve('testWriteFileSyncInvalid.txt');

0 commit comments

Comments
(0)