Dynamically load Javascript functions

Greg

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?

barry-johnson

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();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Dynamically load a JavaScript file

Dynamically load javascript files

Javascript file does not load dynamically

JQuery to load Javascript file dynamically

Javascript dynamically created functions in an object

Javascript prototype functions always load

How to Dynamically Load Internal Scripts In Order With Javascript

Dynamically load JavaScript AND monitor download progress

Dynamically load javascript chunk with webpack and react router

How to load Javascript file in a Service Worker dynamically?

How to dynamically load and use/call a JavaScript file?

How to Dynamically Load Javascript File into HTML

Dynamically load Javascript file one at a time

Javascript: load JSON dynamically (depending on number of files)

Dynamically fetching all class functions in javascript

Dynamically defining an arbitrary number of functions in javascript at runtime

Create onmouseover/onmouseout functions dynamically with javascript?

Javascript variable scope when dynamically referencing functions

How to pass paramters in dynamically created functions in Javascript?

Node.js async module waterfall - dynamically load and execute functions

Firing multiple javascript functions on page load

Problems with firing two javascript functions on page load

JavaScript ES6 Dynamically load class and check if it was loaded?

How to load third-party javascript dynamically in client side blazor?

Load javascript file dynamically by appending script tag to body

Dynamically load external javascript file from Angular component

How to dynamically load a JAR file with Vert.x JavaScript?

How to load gtag.js (Google analytics) dynamically in javascript

Load External Javascript Files Dynamically Based on User Input