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 <[email protected]> Reviewed-By: Ron Korving <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 04af697 commit 44ef458

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

lib/internal/fs/promises.js

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

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

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

460460
async function readFile(path, options) {
461461
options = getOptions(options, { flag: 'r' });
462+
const flag = options.flag || 'r';
462463

463464
if (path instanceof FileHandle)
464465
return readFileHandle(path, options);
465466

466-
const fd = await open(path, options.flag, 0o666);
467+
const fd = await open(path, flag, 0o666);
467468
return readFileHandle(fd, options).finally(fd.close.bind(fd));
468469
}
469470

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
const assert = require('assert');
5+
const { promises: fs } = require('fs');
6+
const fixtures = require('../common/fixtures');
7+
8+
const fn = 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

+4
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)