Last active
August 29, 2015 14:15
-
-
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.
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
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