Created
March 23, 2013 22:41
-
-
Save jrf0110/5229614 to your computer and use it in GitHub Desktop.
Node.js require a directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Require a directory of javascript modules | |
* | |
* Each file in the directory is a key in the returning object | |
* If recursive: true is specified in the options, directories | |
* will be followed. The directory name will be the key and the | |
* value be the result of requireDir on that directory | |
* | |
* {path} [String] - Path to the directory | |
* {options} [Object] - Additional options | |
* {returns} [Object] - Resulting modules inside of an object | |
*/ | |
module.exports = function requireDir(path, options){ | |
var defaults = { | |
recursive: false // Follow directories | |
, relativeToProcess: true // Use process.cwd() as ./ | |
, ignoreIndex: true // Skip index.js files | |
}; | |
if (options){ | |
for (var key in defaults){ | |
if (!options.hasOwnProperty(key)) options[key] = defaults[key]; | |
} | |
} else { | |
options = defaults; | |
} | |
var modules = {}; | |
if (path.substring(0, 2) === "./") | |
path = (options.relativeToProcess ? process.cwd() : __dirname) + path.substring(1); | |
var files = fs.readdirSync(path); | |
for (var i = files.length - 1, name, stat, isModule; i >= 0; i--){ | |
name = files[i]; | |
isModule = false; | |
if (options.ignoreIndex && name === "index.js") continue; | |
stat = fs.statSync(path + '/' + name); | |
if (name.substring(name.length - 3) === ".js"){ | |
name = name.substring(0, name.length - 3); | |
isModule = true; | |
} | |
else if (name.substring(name.length - 5) === ".json"){ | |
name = name.substring(0, name.length - 5); | |
isModule = true; | |
} | |
if (options.recursive && stat.isDirectory()) | |
modules[name] = exports.requireDir(path + '/' + name, options); | |
else if (isModule) modules[name] = require(path + '/' + name); | |
} | |
return modules; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment