Skip to content

Commit 1f40b2a

Browse files
committed
fs: add type checking to makeCallback()
This commit adds proper type checking to makeCallback(). Anything other than undefined or a function will throw. PR-URL: #866 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Vladimir Kurchatkin <[email protected]>
1 parent c82e580 commit 1f40b2a

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

lib/fs.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,14 @@ function maybeCallback(cb) {
6565
// for callbacks that are passed to the binding layer, callbacks that are
6666
// invoked from JS already run in the proper scope.
6767
function makeCallback(cb) {
68-
if (typeof cb !== 'function') {
68+
if (cb === undefined) {
6969
return rethrow();
7070
}
7171

72+
if (typeof cb !== 'function') {
73+
throw new TypeError('callback must be a function');
74+
}
75+
7276
return function() {
7377
return cb.apply(null, arguments);
7478
};
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
var fs = require('fs');
4+
5+
function test(cb) {
6+
return function() {
7+
// fs.stat() calls makeCallback() on its second argument
8+
fs.stat(__filename, cb);
9+
};
10+
}
11+
12+
// Verify the case where a callback function is provided
13+
assert.doesNotThrow(test(function() {}));
14+
15+
// Passing undefined calls rethrow() internally, which is fine
16+
assert.doesNotThrow(test(undefined));
17+
18+
// Anything else should throw
19+
assert.throws(test(null));
20+
assert.throws(test(true));
21+
assert.throws(test(false));
22+
assert.throws(test(1));
23+
assert.throws(test(0));
24+
assert.throws(test('foo'));
25+
assert.throws(test(/foo/));
26+
assert.throws(test([]));
27+
assert.throws(test({}));

0 commit comments

Comments
 (0)