mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
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: https://github.com/nodejs/node/pull/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>
This commit is contained in:
1 parent
04af69750c
commit
44ef458d9c
3 files changed
+26
-2
No files matched your search
@@ -137,7 +137,7 @@ async function readFileHandle(filehandle, options) {
|
||||
}
|
||||
|
||||
if (size === 0)
|
||||
return Buffer.alloc(0);
|
||||
return options.encoding ? '' : Buffer.alloc(0);
|
||||
|
||||
if (size > kMaxLength)
|
||||
throw new ERR_FS_FILE_TOO_LARGE(size);
|
||||
@@ -459,11 +459,12 @@ async function appendFile(path, data, options) {
|
||||
|
||||
async function readFile(path, options) {
|
||||
options = getOptions(options, { flag: 'r' });
|
||||
const flag = options.flag || 'r';
|
||||
|
||||
if (path instanceof FileHandle)
|
||||
return readFileHandle(path, options);
|
||||
|
||||
const fd = await open(path, options.flag, 0o666);
|
||||
const fd = await open(path, flag, 0o666);
|
||||
return readFileHandle(fd, options).finally(fd.close.bind(fd));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
|
||||
const assert = require('assert');
|
||||
const { promises: fs } = require('fs');
|
||||
const fixtures = require('../common/fixtures');
|
||||
|
||||
const fn = fixtures.path('empty.txt');
|
||||
|
||||
common.crashOnUnhandledRejection();
|
||||
|
||||
fs.readFile(fn)
|
||||
.then(assert.ok);
|
||||
|
||||
fs.readFile(fn, 'utf8')
|
||||
.then(assert.strictEqual.bind(this, ''));
|
||||
|
||||
fs.readFile(fn, { encoding: 'utf8' })
|
||||
.then(assert.strictEqual.bind(this, ''));
|
||||
@@ -38,5 +38,9 @@ fs.readFile(fn, 'utf8', function(err, data) {
|
||||
assert.strictEqual('', data);
|
||||
});
|
||||
|
||||
fs.readFile(fn, { encoding: 'utf8' }, function(err, data) {
|
||||
assert.strictEqual('', data);
|
||||
});
|
||||
|
||||
assert.ok(fs.readFileSync(fn));
|
||||
assert.strictEqual('', fs.readFileSync(fn, 'utf8'));
|
||||
Reference in new issue
Block a user