Skip to content

Commit

Permalink
fs: add type checking to makeCallback()
Browse files Browse the repository at this point in the history
This commit adds proper type checking to makeCallback(). Anything
other than undefined or a function will throw.

PR-URL: #866
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Vladimir Kurchatkin <vladimir.kurchatkin@gmail.com>
  • Loading branch information
cjihrig committed Feb 21, 2015
1 parent c82e580 commit 1f40b2a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,14 @@ function maybeCallback(cb) {
// for callbacks that are passed to the binding layer, callbacks that are
// invoked from JS already run in the proper scope.
function makeCallback(cb) {
if (typeof cb !== 'function') {
if (cb === undefined) {
return rethrow();
}

if (typeof cb !== 'function') {
throw new TypeError('callback must be a function');
}

return function() {
return cb.apply(null, arguments);
};
Expand Down
27 changes: 27 additions & 0 deletions test/parallel/test-fs-make-callback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var common = require('../common');
var assert = require('assert');
var fs = require('fs');

function test(cb) {
return function() {
// fs.stat() calls makeCallback() on its second argument
fs.stat(__filename, cb);
};
}

// Verify the case where a callback function is provided
assert.doesNotThrow(test(function() {}));

// Passing undefined calls rethrow() internally, which is fine
assert.doesNotThrow(test(undefined));

// Anything else should throw
assert.throws(test(null));
assert.throws(test(true));
assert.throws(test(false));
assert.throws(test(1));
assert.throws(test(0));
assert.throws(test('foo'));
assert.throws(test(/foo/));
assert.throws(test([]));
assert.throws(test({}));

0 comments on commit 1f40b2a

Please sign in to comment.