Last active
September 6, 2019 00:56
-
-
Save jymcheong/808a57c78e9cd7348b1a39a437651676 to your computer and use it in GitHub Desktop.
Dynamically Loading NodeJS Module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
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
Idea from https://stackoverflow.com/questions/10914751/loading-node-js-modules-dynamically-based-on-route