fs: do not pass Buffer when toString() fails

Even though an Error object is passed to the callback when readFile()
fails due to toString() failing, it is a bit strange to still see
data passed as the second argument. This commit changes that and only
passes the Error object in that case.

PR-URL: https://github.com/nodejs/node/pull/9670
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
Reviewed-By: Prince John Wesley <princejohnwesley@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Brian White 2016-11-17 22:03:39 -05:00
parent 4f97a146ff
commit f3cf8e9808
No known key found for this signature in database
GPG Key ID: 606D7358F94DA209
2 changed files with 5 additions and 7 deletions

View File

@ -396,8 +396,8 @@ function readFileAfterClose(err) {
var buffer = null; var buffer = null;
var callback = context.callback; var callback = context.callback;
if (context.err) if (context.err || err)
return callback(context.err); return callback(context.err || err);
if (context.size === 0) if (context.size === 0)
buffer = Buffer.concat(context.buffers, context.pos); buffer = Buffer.concat(context.buffers, context.pos);
@ -406,8 +406,6 @@ function readFileAfterClose(err) {
else else
buffer = context.buffer; buffer = context.buffer;
if (err) return callback(err, buffer);
if (context.encoding) { if (context.encoding) {
return tryToString(buffer, context.encoding, callback); return tryToString(buffer, context.encoding, callback);
} }
@ -416,13 +414,12 @@ function readFileAfterClose(err) {
} }
function tryToString(buf, encoding, callback) { function tryToString(buf, encoding, callback) {
var e = null;
try { try {
buf = buf.toString(encoding); buf = buf.toString(encoding);
} catch (err) { } catch (err) {
e = err; return callback(err);
} }
callback(e, buf); callback(null, buf);
} }
function tryStatSync(fd, isUserFd) { function tryStatSync(fd, isUserFd) {

View File

@ -33,6 +33,7 @@ stream.on('finish', common.mustCall(function() {
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) { fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
assert.ok(err instanceof Error); assert.ok(err instanceof Error);
assert.strictEqual('"toString()" failed', err.message); assert.strictEqual('"toString()" failed', err.message);
assert.strictEqual(buf, undefined);
})); }));
})); }));