Skip to content

Instantly share code, notes, and snippets.

@kwal
Last active August 29, 2015 14:21
Show Gist options
  • Save kwal/bad7e497033332813cef to your computer and use it in GitHub Desktop.
Save kwal/bad7e497033332813cef to your computer and use it in GitHub Desktop.
Module Loader
var fs = require('fs'),
path = require('path');
module.exports = function(dir, ignore) {
var result = {};
loadModules(dir, result, ignore);
return result;
};
function convertToCamelCase(value) {
return value.replace(/[-_]([a-z])/g, function(g) {
return g[1].toUpperCase();
});
}
function loadModules(dir, target, ignore) {
ignore || (ignore = []);
fs.readdirSync(dir).forEach(function(item) {
var itemPath = path.resolve(dir, item),
camelCasedItem = convertToCamelCase(item),
name = path.basename(item, '.js'),
camelCasedName = convertToCamelCase(name),
stat = fs.statSync(itemPath);
if (stat.isDirectory()) {
if (ignore.indexOf(item) !== -1) {
return;
}
target[camelCasedItem] = {};
loadModules(itemPath, target[camelCasedItem]);
} else {
if (name === 'index' || ignore.indexOf(name) !== -1) {
return;
}
target[camelCasedName] = require(itemPath);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment