Skip to content

Instantly share code, notes, and snippets.

@jymcheong
Last active September 6, 2019 00:56
Show Gist options
  • Save jymcheong/808a57c78e9cd7348b1a39a437651676 to your computer and use it in GitHub Desktop.
Save jymcheong/808a57c78e9cd7348b1a39a437651676 to your computer and use it in GitHub Desktop.
Dynamically Loading NodeJS Module
var fs = require('fs');
var path_module = require('path');
var module_holder = {};
function LoadModules(path) {
return new Promise(resolve => {
fs.readdirSync(path).forEach(file => {
require(path + '/' + file)(module_holder);
});
resolve(module_holder);
});
}
(async function() {
var DIR = path_module.join(__dirname, 'lib');
module_holder = await LoadModules(DIR);
const chokidar = require('chokidar');
chokidar.watch(DIR, {ignored: /(^|[\/\\])\../, persistent: true})
.on('change', path => {
let changedModuleName = path.replace(DIR + '/','').replace('.js','');
console.log(path + ' changed');
delete require.cache[require.resolve(path)];
require(path)(module_holder);
module_holder[changedModuleName]()
})
})();
exports.module_holder = module_holder;
function handler(req, res) {
console.log('Entered my cool script!!!');
}
module.exports = function(module_holder) {
// the key in this dictionary can be whatever you want
// just make sure it won't override other modules
module_holder['user_getDetails'] = handler;
};
@jymcheong
Copy link
Author

This is just PoC. It needs more error handling (eg. check if the changed path is actually a module file).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment