diff --git a/lib/fs.js b/lib/fs.js index a5e8f95c151f9e..fbb2f47b0f438e 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -609,6 +609,12 @@ fs.read = function(fd, buffer, offset, length, position, callback) { }; } + if (length === 0) { + return process.nextTick(function() { + callback && callback(null, 0, buffer); + }); + } + function wrapper(err, bytesRead) { // Retain a reference to buffer so that it can't be GC'ed too soon. callback && callback(err, bytesRead || 0, buffer); @@ -648,6 +654,14 @@ fs.readSync = function(fd, buffer, offset, length, position) { offset = 0; } + if (length === 0) { + if (legacy) { + return ['', 0]; + } else { + return 0; + } + } + var r = binding.read(fd, buffer, offset, length, position); if (!legacy) { return r; diff --git a/test/parallel/test-fs-read-buffer-zero-length.js b/test/parallel/test-fs-read-buffer-zero-length.js new file mode 100644 index 00000000000000..96586c25041c05 --- /dev/null +++ b/test/parallel/test-fs-read-buffer-zero-length.js @@ -0,0 +1,19 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const Buffer = require('buffer').Buffer; +const fs = require('fs'); +const filepath = path.join(common.fixturesDir, 'x.txt'); +const fd = fs.openSync(filepath, 'r'); +const bufferAsync = new Buffer(0); +const bufferSync = new Buffer(0); + +fs.read(fd, bufferAsync, 0, 0, 0, common.mustCall(function(err, bytesRead) { + assert.equal(bytesRead, 0); + assert.deepEqual(bufferAsync, new Buffer(0)); +})); + +const r = fs.readSync(fd, bufferSync, 0, 0, 0); +assert.deepEqual(bufferSync, new Buffer(0)); +assert.equal(r, 0); diff --git a/test/parallel/test-fs-read-zero-length.js b/test/parallel/test-fs-read-zero-length.js new file mode 100644 index 00000000000000..9c4cde52362ccc --- /dev/null +++ b/test/parallel/test-fs-read-zero-length.js @@ -0,0 +1,18 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); +const filepath = path.join(common.fixturesDir, 'x.txt'); +const fd = fs.openSync(filepath, 'r'); +const expected = ''; + +fs.read(fd, 0, 0, 'utf-8', common.mustCall(function(err, str, bytesRead) { + assert.ok(!err); + assert.equal(str, expected); + assert.equal(bytesRead, 0); +})); + +const r = fs.readSync(fd, 0, 0, 'utf-8'); +assert.equal(r[0], expected); +assert.equal(r[1], 0);