Skip to content

Commit 44ef458

Browse files
bdistinaddaleax
authored andcommitted
fs: ensure options.flag defaults to 'r' in readFile
When passing {} or { encoding: 'utf8' } as options to readFile, the flag is not defaulted to 'r' unlike normal fs. This fix makes fs.promises.readFile() act consistent with fs.readFile(). It also fixes another issue with fs.promises.readfile() where it returned a Buffer instead of an empty string when encoding is provided. PR-URL: #20268 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Ron Korving <ron@ronkorving.nl> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
1 parent 04af697 commit 44ef458

3 files changed

Lines changed: 26 additions & 2 deletions

File tree

‎lib/internal/fs/promises.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ async function readFileHandle(filehandle, options) {
137137
}
138138

139139
if(size===0)
140-
returnBuffer.alloc(0);
140+
returnoptions.encoding ? '' : Buffer.alloc(0);
141141

142142
if(size>kMaxLength)
143143
thrownewERR_FS_FILE_TOO_LARGE(size);
@@ -459,11 +459,12 @@ async function appendFile(path, data, options) {
459459

460460
asyncfunctionreadFile(path,options){
461461
options=getOptions(options,{flag: 'r'});
462+
constflag=options.flag||'r';
462463

463464
if(pathinstanceofFileHandle)
464465
returnreadFileHandle(path,options);
465466

466-
constfd=awaitopen(path,options.flag,0o666);
467+
constfd=awaitopen(path,flag,0o666);
467468
returnreadFileHandle(fd,options).finally(fd.close.bind(fd));
468469
}
469470

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
4+
constassert=require('assert');
5+
const{promises: fs}=require('fs');
6+
constfixtures=require('../common/fixtures');
7+
8+
constfn=fixtures.path('empty.txt');
9+
10+
common.crashOnUnhandledRejection();
11+
12+
fs.readFile(fn)
13+
.then(assert.ok);
14+
15+
fs.readFile(fn,'utf8')
16+
.then(assert.strictEqual.bind(this,''));
17+
18+
fs.readFile(fn,{encoding: 'utf8'})
19+
.then(assert.strictEqual.bind(this,''));

‎test/parallel/test-fs-readfile-empty.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,9 @@ fs.readFile(fn, 'utf8', function(err, data) {
3838
assert.strictEqual('',data);
3939
});
4040

41+
fs.readFile(fn,{encoding: 'utf8'},function(err,data){
42+
assert.strictEqual('',data);
43+
});
44+
4145
assert.ok(fs.readFileSync(fn));
4246
assert.strictEqual('',fs.readFileSync(fn,'utf8'));

0 commit comments

Comments
 (0)