public
Last active

Reloading modules from the repl in Node.js

  • Download Gist
reload.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
// Reloading modules from the repl in Node.js
// Benjamin Gleitzman (gleitz@mit.edu)
//
// 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);
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.