Skip to content

Commit 7added3

Browse files
evanlucasrvagg
authored andcommitted
fs: pass err to callback if buffer is too big
In fs.readFile, if an encoding is specified and toString fails, do not throw an error. Instead, pass the error to the callback. Fixes: #2767 PR-URL: #3485 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 1a41feb commit 7added3

File tree

2 files changed

+67
-3
lines changed

2 files changed

+67
-3
lines changed

lib/fs.js

+15-3
Original file line numberDiff line numberDiff line change
@@ -395,12 +395,24 @@ function readFileAfterClose(err) {
395395
else
396396
buffer = context.buffer;
397397

398-
if (context.encoding)
399-
buffer = buffer.toString(context.encoding);
398+
if (err) return callback(err, buffer);
400399

401-
callback(err, buffer);
400+
if (context.encoding) {
401+
return tryToString(buffer, context.encoding, callback);
402+
}
403+
404+
callback(null, buffer);
402405
}
403406

407+
function tryToString(buf, encoding, callback) {
408+
var e;
409+
try {
410+
buf = buf.toString(encoding);
411+
} catch (err) {
412+
e = err;
413+
}
414+
callback(e, buf);
415+
}
404416

405417
fs.readFileSync = function(path, options) {
406418
if (!options) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const fs = require('fs');
6+
const path = require('path');
7+
const kStringMaxLength = process.binding('buffer').kStringMaxLength;
8+
9+
common.refreshTmpDir();
10+
11+
const file = path.join(common.tmpDir, 'toobig.txt');
12+
const stream = fs.createWriteStream(file, {
13+
flags: 'a'
14+
});
15+
16+
const size = kStringMaxLength / 200;
17+
const a = new Buffer(size).fill('a');
18+
19+
for (var i = 0; i < 201; i++) {
20+
stream.write(a);
21+
}
22+
23+
stream.end();
24+
stream.on('finish', common.mustCall(function() {
25+
// make sure that the toString does not throw an error
26+
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
27+
assert.ok(err instanceof Error);
28+
assert.strictEqual('toString failed', err.message);
29+
}));
30+
}));
31+
32+
function destroy() {
33+
try {
34+
fs.unlinkSync(file);
35+
} catch (err) {
36+
// it may not exist
37+
}
38+
}
39+
40+
process.on('exit', destroy);
41+
42+
process.on('SIGINT', function() {
43+
destroy();
44+
process.exit();
45+
});
46+
47+
// To make sure we don't leave a very large file
48+
// on test machines in the event this test fails.
49+
process.on('uncaughtException', function(err) {
50+
destroy();
51+
throw err;
52+
});

0 commit comments

Comments
 (0)