diff --git a/lib/fs.js b/lib/fs.js index d407cf1479eac0..f9223f5ca8484f 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -397,8 +397,8 @@ function readFileAfterClose(err) { var buffer = null; var callback = context.callback; - if (context.err) - return callback(context.err); + if (context.err || err) + return callback(context.err || err); if (context.size === 0) buffer = Buffer.concat(context.buffers, context.pos); @@ -407,8 +407,6 @@ function readFileAfterClose(err) { else buffer = context.buffer; - if (err) return callback(err, buffer); - if (context.encoding) { return tryToString(buffer, context.encoding, callback); } @@ -417,13 +415,12 @@ function readFileAfterClose(err) { } function tryToString(buf, encoding, callback) { - var e = null; try { buf = buf.toString(encoding); } catch (err) { - e = err; + return callback(err); } - callback(e, buf); + callback(null, buf); } function tryStatSync(fd, isUserFd) { diff --git a/test/parallel/test-fs-readfile-tostring-fail.js b/test/parallel/test-fs-readfile-tostring-fail.js index 8ed9658a25889a..f3d728f57f7aeb 100644 --- a/test/parallel/test-fs-readfile-tostring-fail.js +++ b/test/parallel/test-fs-readfile-tostring-fail.js @@ -33,6 +33,7 @@ stream.on('finish', common.mustCall(function() { fs.readFile(file, 'utf8', common.mustCall(function(err, buf) { assert.ok(err instanceof Error); assert.strictEqual('"toString()" failed', err.message); + assert.strictEqual(buf, undefined); })); }));