Written by Robert Whitney Category: Programming

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)
        var plugin = require(file);
        Plugins[plugin.name] = plugin;

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

/* ... */