Skip to content

Instantly share code, notes, and snippets.

@jrf0110
Created March 23, 2013 22:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrf0110/5229614 to your computer and use it in GitHub Desktop.
Save jrf0110/5229614 to your computer and use it in GitHub Desktop.
Node.js require a directory
/**
* 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