Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs/promises: ensure options.flag is defaulted to 'r' in readFile #20268

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,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 @@ -463,11 +463,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');

This comment was marked as resolved.


common.crashOnUnhandledRejection();

fs.readFile(fn)
.then(assert.ok);

fs.readFile(fn, 'utf8')
.then(assert.strictEqual.bind(this, ''));

This comment was marked as resolved.


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'));