Skip to content

Instantly share code, notes, and snippets.

@endaaman
Last active March 21, 2016 21:09
Show Gist options
  • Save endaaman/e78b5c6e327c4b2ed719 to your computer and use it in GitHub Desktop.
Save endaaman/e78b5c6e327c4b2ed719 to your computer and use it in GitHub Desktop.
How to get module caches which the module is depending on and remove them
function extractDependingModuleCaches(name) {
function inner(name, targets) {
targets[name] = true
Object.keys(require.cache[name].children).forEach(function(key) {
var child = require.cache[name].children[key]
inner(child.filename, targets)
})
return targets
}
return targets = Object.keys(inner(name, {}))
}
function removeDependingModuleCaches(name, filter) {
var targets = extractDependingModuleCaches(name)
targets.forEach(function(name) {
if (typeof filter !== 'function' || filter(name)) {
delete require.cache[name]
}
})
}
module.exports = {
extractDependingModuleCaches,
removeDependingModuleCaches,
}
// a.js
console.log('entered A')

module.exports = `A(id: ${Math.floor(Math.random()*100)})
// b.js
var a = require('./a')
console.log('entered B')
module.exports = `${a}\nB(id: ${Math.floor(Math.random()*100)})`
// c.js
var b = require('./b')
console.log('entered C')
module.exports = `${b}\nC(id: ${Math.floor(Math.random()*100)})`

c.js -> b.js -> a.js

var u = require('./manage_module_cache')


var old_c = require('./c')

console.log('[old_c]')
console.log(old_c)

console.log('\nremoving\n')
u.removeDependingModuleCaches(require.resolve('./c'))


console.log('[old_c]')
console.log(old_c)
var new_c = require('./c')
console.log('[new_c]')
console.log(new_c)

outputs

entered A
entered B
entered C
[old_c]
A(id: 88)
B(id: 64)
C(id: 27)



removing



[old_c]
A(id: 88)
B(id: 64)
C(id: 27)
entered A
entered B
entered C
[new_c]
A(id: 63)
B(id: 71)
C(id: 88)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment