diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index a80a5283c52e3c..97ac4c6c495b3d 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -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)); } diff --git a/test/parallel/test-fs-promises-readfile-empty.js b/test/parallel/test-fs-promises-readfile-empty.js new file mode 100644 index 00000000000000..24c17655c62135 --- /dev/null +++ b/test/parallel/test-fs-promises-readfile-empty.js @@ -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, '')); diff --git a/test/parallel/test-fs-readfile-empty.js b/test/parallel/test-fs-readfile-empty.js index 21f99fc6be24ba..36eccfb1162713 100644 --- a/test/parallel/test-fs-readfile-empty.js +++ b/test/parallel/test-fs-readfile-empty.js @@ -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'));