Created
April 23, 2012 09:13
-
-
Save pasaran/2469754 to your computer and use it in GitHub Desktop.
Require all modules in directory
This file contains hidden or 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
// --------------------------------------------------------------------------------------------------------------- // | |
var fs_ = require('fs'); | |
var path_ = require('path'); | |
// --------------------------------------------------------------------------------------------------------------- // | |
var basedir = path_.dirname(module.parent.filename); | |
/** | |
Loads all modules in a directory. | |
var requireAll = require('./require-all.js'); | |
// Load ./modules/*.js | |
requireAll('modules'); | |
// Load ./modules/foo.*.js | |
requireAll('modules', /^foo/); | |
@param {String} dirname Path to a directory. | |
@param {RegExp=} regexp Optional regexp to filter filenames. By default requireAll will look for all .js files. | |
*/ | |
function requireAll(dirname, regexp) { | |
// Resolve relative path. | |
if ( !/^\//.test(dirname) ) { | |
dirname = path_.join(basedir, dirname); | |
} | |
fs_.readdirSync(dirname).forEach(function(filename) { | |
if ( /\.js$/.test(filename) && ( !regexp || regexp.test(filename) ) ) { | |
var path = path_.join(dirname, filename); | |
require(path); | |
} | |
}); | |
}; | |
// --------------------------------------------------------------------------------------------------------------- // | |
module.exports = requireAll; | |
// --------------------------------------------------------------------------------------------------------------- // | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment