Skip to content

Commit b500706

Browse files
ferossMichael Scovetta
authored and
Michael Scovetta
committed
fs: fs.read into zero buffer should not throw exception
Fixes: nodejs#4517. PR-URL: nodejs#4518 Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent a161031 commit b500706

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

lib/fs.js

+14
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,12 @@ fs.read = function(fd, buffer, offset, length, position, callback) {
609609
};
610610
}
611611

612+
if (length === 0) {
613+
return process.nextTick(function() {
614+
callback && callback(null, 0, buffer);
615+
});
616+
}
617+
612618
function wrapper(err, bytesRead) {
613619
// Retain a reference to buffer so that it can't be GC'ed too soon.
614620
callback && callback(err, bytesRead || 0, buffer);
@@ -648,6 +654,14 @@ fs.readSync = function(fd, buffer, offset, length, position) {
648654
offset = 0;
649655
}
650656

657+
if (length === 0) {
658+
if (legacy) {
659+
return ['', 0];
660+
} else {
661+
return 0;
662+
}
663+
}
664+
651665
var r = binding.read(fd, buffer, offset, length, position);
652666
if (!legacy) {
653667
return r;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const path = require('path');
5+
const Buffer = require('buffer').Buffer;
6+
const fs = require('fs');
7+
const filepath = path.join(common.fixturesDir, 'x.txt');
8+
const fd = fs.openSync(filepath, 'r');
9+
const bufferAsync = new Buffer(0);
10+
const bufferSync = new Buffer(0);
11+
12+
fs.read(fd, bufferAsync, 0, 0, 0, common.mustCall(function(err, bytesRead) {
13+
assert.equal(bytesRead, 0);
14+
assert.deepEqual(bufferAsync, new Buffer(0));
15+
}));
16+
17+
const r = fs.readSync(fd, bufferSync, 0, 0, 0);
18+
assert.deepEqual(bufferSync, new Buffer(0));
19+
assert.equal(r, 0);
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const path = require('path');
5+
const fs = require('fs');
6+
const filepath = path.join(common.fixturesDir, 'x.txt');
7+
const fd = fs.openSync(filepath, 'r');
8+
const expected = '';
9+
10+
fs.read(fd, 0, 0, 'utf-8', common.mustCall(function(err, str, bytesRead) {
11+
assert.ok(!err);
12+
assert.equal(str, expected);
13+
assert.equal(bytesRead, 0);
14+
}));
15+
16+
const r = fs.readSync(fd, 0, 0, 'utf-8');
17+
assert.equal(r[0], expected);
18+
assert.equal(r[1], 0);

0 commit comments

Comments
 (0)