Greg
Greg

Reputation: 2609

Dynamically load Javascript functions

I'd like to dynamically load and call Javascript functions with a JSON file. The idea is to build a plugin framework that would others to add functionality by simply writing a function and updating the JSON file.

For example, with the following JSON:

{
"plugins" : {
    "random" : {
        "name"  : "Random number generator",
        "hook"  : "random"
    }
}
}

... and the following plugin: random.js

module.exports.run = function() {
    return Math.round(Math.random() * 100);
}

I'd like to be able to parse the JSON file and call the run function of any plugin. How can I load and call the run function on random?

Upvotes: 0

Views: 664

Answers (1)

barry-johnson
barry-johnson

Reputation: 3224

Based on what you have described above, just require the module.

var plugins = require('./plugins.json');
var pluginKeys = Object.keys(plugins);
for (var i = 0; i< pluginKeys; i++)
    plugins[pluginKeys[i]].func = require('./'+[pluginKeys[i].hook+'.js').run;

// could add extra path to above as well. You could also leave off the '.js'

Then you would just:

var randomTheHardWay = plugins.random.func();

Upvotes: 2

Related Questions