Skip to content

Commit df5acf7

Browse files
mscdexItalo A. Casas
authored andcommitted
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: nodejs#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>
1 parent 6e62353 commit df5acf7

2 files changed

Lines changed: 5 additions & 7 deletions

File tree

lib/fs.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -397,8 +397,8 @@ function readFileAfterClose(err) {
397397
var buffer = null;
398398
var callback = context.callback;
399399

400-
if (context.err)
401-
return callback(context.err);
400+
if (context.err || err)
401+
return callback(context.err || err);
402402

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

410-
if (err) return callback(err, buffer);
411-
412410
if (context.encoding) {
413411
return tryToString(buffer, context.encoding, callback);
414412
}
@@ -417,13 +415,12 @@ function readFileAfterClose(err) {
417415
}
418416

419417
function tryToString(buf, encoding, callback) {
420-
var e = null;
421418
try {
422419
buf = buf.toString(encoding);
423420
} catch (err) {
424-
e = err;
421+
return callback(err);
425422
}
426-
callback(e, buf);
423+
callback(null, buf);
427424
}
428425

429426
function tryStatSync(fd, isUserFd) {

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

Lines changed: 1 addition & 0 deletions
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)