Last active
May 7, 2019 21:48
-
-
Save gleitz/6896099 to your computer and use it in GitHub Desktop.
Reloading modules from the repl in Node.js
This file contains 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
// Reloading modules from the repl in Node.js | |
// Benjamin Gleitzman ([email protected]) | |
// | |
// Inspired by Ben Barkay | |
// http://stackoverflow.com/a/14801711/305414 | |
// | |
// Usage: `node reload.js` | |
// You can load the module as usual | |
// var mymodule = require('./mymodule') | |
// And the reload it when needed | |
// mymodule = require.reload('./mymodule') | |
// | |
// I suggest using an alias in your .bashrc/.profile: | |
// alias node_reload='node /path/to/reload.js' | |
var myrepl = require("repl").start({}); | |
/** | |
* Removes a module from the cache. | |
*/ | |
myrepl.context.require.uncache = function (moduleName) { | |
// Run over the cache looking for the files | |
// loaded by the specified module name | |
myrepl.context.require.searchCache(moduleName, function (mod) { | |
delete require.cache[mod.id]; | |
}); | |
}; | |
/** | |
* Runs over the cache to search for all the cached files. | |
*/ | |
myrepl.context.require.searchCache = function (moduleName, callback) { | |
// Resolve the module identified by the specified name | |
var mod = require.resolve(moduleName); | |
// Check if the module has been resolved and found within | |
// the cache | |
if (mod && ((mod = require.cache[mod]) !== undefined)) { | |
// Recursively go over the results | |
(function run(mod) { | |
// Go over each of the module's children and | |
// run over it | |
mod.children.forEach(function (child) { | |
run(child); | |
}); | |
// Call the specified callback providing the | |
// found module | |
callback(mod); | |
})(mod); | |
} | |
}; | |
/* | |
* Load a module, clearing it from the cache if necessary. | |
*/ | |
myrepl.context.require.reload = function(moduleName) { | |
myrepl.context.require.uncache(moduleName); | |
return myrepl.context.require(moduleName); | |
}; |
What is a module "repl"?
Hello, maybe you can have a look at my module-invalidate.
It allows you to invalidate a module and then make it automatically reloaded on further access, without the need to call require() again.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code seems to not be resetting some that it should. After 'many' reloads, I get this error:
I have to assume that it is something in the log4js modules that is messing things up.