fs: account for buffer alloc failure in readFile

PR-URL: https://github.com/nodejs/node/pull/16219
Refs: https://github.com/nodejs/node/pull/15362
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
This commit is contained in:
Anna Henningsen 2017-10-15 13:18:09 +02:00 committed by Ruben Bridgewater
parent 5a17ab3ff3
commit 5cde451ffd
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
2 changed files with 18 additions and 19 deletions

View File

@ -472,7 +472,11 @@ function readFileAfterStat(err) {
return context.close(err);
}
context.buffer = Buffer.allocUnsafeSlow(size);
try {
context.buffer = Buffer.allocUnsafeSlow(size);
} catch (err) {
return context.close(err);
}
context.read();
}
@ -507,27 +511,21 @@ function readFileAfterClose(err) {
if (context.err || err)
return callback(context.err || err);
if (context.size === 0)
buffer = Buffer.concat(context.buffers, context.pos);
else if (context.pos < context.size)
buffer = context.buffer.slice(0, context.pos);
else
buffer = context.buffer;
if (context.encoding) {
return tryToString(buffer, context.encoding, callback);
}
callback(null, buffer);
}
function tryToString(buf, encoding, callback) {
try {
buf = buf.toString(encoding);
if (context.size === 0)
buffer = Buffer.concat(context.buffers, context.pos);
else if (context.pos < context.size)
buffer = context.buffer.slice(0, context.pos);
else
buffer = context.buffer;
if (context.encoding)
buffer = buffer.toString(context.encoding);
} catch (err) {
return callback(err);
}
callback(null, buf);
callback(null, buffer);
}
function tryStatSync(fd, isUserFd) {

View File

@ -29,7 +29,8 @@ stream.on('finish', common.mustCall(function() {
// make sure that the toString does not throw an error
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
assert.ok(err instanceof Error);
assert.strictEqual('"toString()" failed', err.message);
assert(/^(Array buffer allocation failed|"toString\(\)" failed)$/
.test(err.message));
assert.strictEqual(buf, undefined);
}));
}));