Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created September 20, 2018 17:31
Show Gist options
  • Save dead-claudia/6f983913e9bacd7cf7ddfa4c6e81f80e to your computer and use it in GitHub Desktop.
Save dead-claudia/6f983913e9bacd7cf7ddfa4c6e81f80e to your computer and use it in GitHub Desktop.
var Module = require("module")
function requireUncached(file, baseDir) {
// Hack: hijack Node's internal resolution algorithm to require the file
// as if from a fake module in the correct base directory. It also will
// avoid several bugs with the `resolve` module (Node's is necessarily
// more stable).
var dirname = path.resolve(baseDir)
var m = new Module(path.join(dirname, "dummy.js"))
m.filename = m.id
m.paths = Module._nodeModulePaths(dirname)
m.loaded = true
// eslint-disable-next-line global-require
var exports = m.require(file)
// Remove the module and its children from the cache and dereference all
// `require`d children from their parent. This implies all scripts
// loaded are not cached, which helps cut down on persistent memory
// usage some (especially when loading tests).
delete Module._cache[m.filename]
for (var i = 0; i < m.children.length; i++) {
delete Module._cache[m.children[i].filename]
}
m.children.length = 0
return exports
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment