Skip to content

Commit f3cf8e9

Browse files
committed
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: #9670 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: Prince John Wesley <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 4f97a14 commit f3cf8e9

File tree

2 files changed

+5
-7
lines changed

2 files changed

+5
-7
lines changed

lib/fs.js

+4-7
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,8 @@ function readFileAfterClose(err) {
396396
var buffer = null;
397397
var callback = context.callback;
398398

399-
if (context.err)
400-
return callback(context.err);
399+
if (context.err || err)
400+
return callback(context.err || err);
401401

402402
if (context.size === 0)
403403
buffer = Buffer.concat(context.buffers, context.pos);
@@ -406,8 +406,6 @@ function readFileAfterClose(err) {
406406
else
407407
buffer = context.buffer;
408408

409-
if (err) return callback(err, buffer);
410-
411409
if (context.encoding) {
412410
return tryToString(buffer, context.encoding, callback);
413411
}
@@ -416,13 +414,12 @@ function readFileAfterClose(err) {
416414
}
417415

418416
function tryToString(buf, encoding, callback) {
419-
var e = null;
420417
try {
421418
buf = buf.toString(encoding);
422419
} catch (err) {
423-
e = err;
420+
return callback(err);
424421
}
425-
callback(e, buf);
422+
callback(null, buf);
426423
}
427424

428425
function tryStatSync(fd, isUserFd) {

test/parallel/test-fs-readfile-tostring-fail.js

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ stream.on('finish', common.mustCall(function() {
3333
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
3434
assert.ok(err instanceof Error);
3535
assert.strictEqual('"toString()" failed', err.message);
36+
assert.strictEqual(buf, undefined);
3637
}));
3738
}));
3839

0 commit comments

Comments
 (0)