Skip to content

Instantly share code, notes, and snippets.

@dweinstein
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dweinstein/de0ae7a491d1eeb33a89 to your computer and use it in GitHub Desktop.
Save dweinstein/de0ae7a491d1eeb33a89 to your computer and use it in GitHub Desktop.
javascript / node: load / require a directory of modules and bind arguments to each returning a single object with all the methods. This is useful for example if you'd like to bind a series of utility methods to the same database object.
var fmt = require('util').format;
var join = require('path').join;
module.exports = function loadAndBind(path) {
var methods = {};
var normalizedPath = join(__dirname, path);
var args = [].slice.call(arguments, 1);
require("fs").readdirSync(normalizedPath).forEach(function(file) {
var mod = require(join(normalizedPath, file));
if (methods[mod.name]) {
throw fmt("Existing method with name %s", mod.name);
}
methods[mod.name] = mod.bind.apply(mod, [].concat(mod, args));
});
return methods;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment