Skip to content
Permalink
Browse files

fs: fs.read into zero buffer should not throw exception

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 2b15e68bbee031eb7d027efa24fb6a220f823c82
Showing with 51 additions and 0 deletions.
  1. +14 −0 lib/fs.js
  2. +19 −0 test/parallel/test-fs-read-buffer-zero-length.js
  3. +18 −0 test/parallel/test-fs-read-zero-length.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;
@@ -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);
@@ -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.
You can’t perform that action at this time.