Skip to content

Commit

Permalink
fs: fs.read into zero buffer should not throw exception
Browse files Browse the repository at this point in the history
Fixes: #4517.
PR-URL: #4518
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
feross authored and jasnell committed Jan 6, 2016
1 parent 3b27dd5 commit 2b15e68
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions test/parallel/test-fs-read-buffer-zero-length.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 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);
18 changes: 18 additions & 0 deletions test/parallel/test-fs-read-zero-length.js
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit 2b15e68

Please sign in to comment.