Skip to content

Commit

Permalink
fs: ensure options.flag defaults to 'r' in readFile
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
bdistin authored and addaleax committed May 31, 2018
1 parent 04af697 commit 44ef458
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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));
}

Expand Down
19 changes: 19 additions & 0 deletions test/parallel/test-fs-promises-readfile-empty.js
Original file line number Diff line number Diff line change
@@ -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, ''));
4 changes: 4 additions & 0 deletions test/parallel/test-fs-readfile-empty.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'));

0 comments on commit 44ef458

Please sign in to comment.