0

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?

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.