diff --git a/index.js b/index.js index cd37da7..ee5b29c 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,7 @@ var fs = require('fs'), defaultOptions = { extensions: ['js', 'json', 'coffee'], recurse: true, + maxDepth: -1, // no max depth rename: function (name) { return name; }, @@ -34,7 +35,7 @@ function checkFileInclusion(path, filename, options) { ); } -function requireDirectory(m, path, options) { +function _requireDirectory(m, path, options, depth) { var retval = {}; // path is optional @@ -62,9 +63,9 @@ function requireDirectory(m, path, options) { key, obj; - if (fs.statSync(joined).isDirectory() && options.recurse) { + if (fs.statSync(joined).isDirectory() && options.recurse && (options.maxDepth < 0 || depth < options.maxDepth)) { // this node is a directory; recurse - files = requireDirectory(m, joined, options); + files = _requireDirectory(m, joined, options, depth + 1); // exclude empty directories if (Object.keys(files).length) { retval[options.rename(filename, joined, filename)] = files; @@ -82,5 +83,9 @@ function requireDirectory(m, path, options) { return retval; } +function requireDirectory(m, path, options) { + return _requireDirectory(m, path, options, 0); +} + module.exports = requireDirectory; module.exports.defaults = defaultOptions; diff --git a/test/example/level1/level2/level3/three.js b/test/example/level1/level2/level3/three.js new file mode 100644 index 0000000..787a4ec --- /dev/null +++ b/test/example/level1/level2/level3/three.js @@ -0,0 +1 @@ +module.exports = "three"; \ No newline at end of file diff --git a/test/example/level1/level2/two.js b/test/example/level1/level2/two.js new file mode 100644 index 0000000..f351dff --- /dev/null +++ b/test/example/level1/level2/two.js @@ -0,0 +1 @@ +module.exports = "two"; \ No newline at end of file diff --git a/test/example/level1/one.js b/test/example/level1/one.js new file mode 100644 index 0000000..bdab7b5 --- /dev/null +++ b/test/example/level1/one.js @@ -0,0 +1 @@ +module.exports = "one"; \ No newline at end of file diff --git a/test/test.js b/test/test.js index bfbe798..4641763 100644 --- a/test/test.js +++ b/test/test.js @@ -209,6 +209,34 @@ assert.equal('baz!', bar.baz); assert.equal('gone and done it', funResult); }); + + test('should recurse 0 times', function () { + //arrange + //act + var test = reqdir(module, PATH_TO_EXAMPLE, {maxDepth: 0}); + //assert + assert.equal(undefined, test.level1); + }); + + test('should only recurse 2 times', function () { + //arrange + //act + var test = reqdir(module, PATH_TO_EXAMPLE, {maxDepth: 2}); + //assert + assert.equal('one', test.level1.one); + assert.equal('two', test.level1.level2.two); + assert.equal(undefined, test.level1.level2.level3); + }); + + test('should still be able to disable recursion with maxDepth set', function () { + //arrange + //act + var test = reqdir(module, PATH_TO_EXAMPLE, {recurse: false, maxDepth: 2}); + + //assert + assert.equal('foo!', test.foo); + assert.equal(undefined, test.bar); + }); }); }());