Skip to content

Commit 2cd3e61

Browse files
bdistinBridgeAR
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 72ccafd commit 2cd3e61

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

lib/internal/fs/promises.js

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

140140
if (size === 0)
141-
return Buffer.alloc(0);
141+
return options.encoding ? '' : Buffer.alloc(0);
142142

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

455455
async function readFile(path, options) {
456456
options = getOptions(options, { flag: 'r' });
457+
const flag = options.flag || 'r';
457458

458459
if (path instanceof FileHandle)
459460
return readFileHandle(path, options);
460461

461-
const fd = await open(path, options.flag, 0o666);
462+
const fd = await open(path, flag, 0o666);
462463
return readFileHandle(fd, options).finally(fd.close.bind(fd));
463464
}
464465

Lines changed: 19 additions & 0 deletions
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

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)