Often times I find myself needing to dynamically load a list of plugins from a file or directory. This example shows how to use glob expression to load every file in a ./plugins/ directory.

First you will need to define a name for your plugin like so, it would also be wise to define a function.


exports.name = 'myPlugin';
exports.doSomething = function()
{
    console.log("action completed");
}
    
Save the file to ./plugins/myPlugin.js.

The following code goes into your main javascript file and loads all of the files in ./plugins/. Once loaded it defines an object with the plugin content so that it can be called upon later.


const glob = require('glob');
var Plugins = {};
glob('./plugins/*.js', {cwd: __dirname}, function(err, files)
{
    files.forEach(function(file){
        var plugin = require(file);
        Plugins[plugin.name] = plugin;
    });
});
    

The following could be used to call your method after the plugin has been loaded:


/* ... */
Plugins.myPlugin.doSomething();
    

Robert Whitney
Nerd off the farm

Geek, Gamer, Blogger, breaker of things & destroyer of @world.
My interests, aside from computers, include playing stringed instruments, listening to old rock music, learning new things, and getting a pizza the action making that dough! My favorite activities to relax include video games, listening to music, reading, watching documentaries, and talking hours on end with my girlfriend from the other side of the country who I met online and seen over Christmas. If you have my on Facebook then you'll know that she's real and totally not made up. Don't add me on Facebook if you don't know me. I don't use Facebook. Leave my Facebook alone.
I love to chill out to the Beatles, and rock out to Metalica, Guns n` Roses, and Ozzy, but my guilty pleasures are Garth Brooks, Kenny Loggins, and Red Sovine.

Robert has authored a total of 10 posts. Robert's last post was 2021-09-01T16:20:00-05:00