Skip to content

Instantly share code, notes, and snippets.

@totherik
Created February 13, 2014 15:24
Show Gist options
  • Save totherik/8977080 to your computer and use it in GitHub Desktop.
Save totherik/8977080 to your computer and use it in GitHub Desktop.
Get a unique instance of any module. Simply call `getFresh(module);`
function getFresh(name) {
var orig, fresh;
orig = snapshot(name);
invalidate(name);
fresh = require(name);
invalidate(name);
restore(orig);
return fresh;
}
function invalidate(module) {
var path, metadata;
path = require.resolve(module);
metadata = require.cache[path];
if (Array.isArray(metadata.children)) {
metadata.children.forEach(function (child) {
invalidate(child.id);
});
}
return delete require.cache[path];
}
function snapshot(module, dest) {
var path, metadata;
dest = dest || [];
path = require.resolve(module);
metadata = require.cache[path];
if (Array.isArray(metadata.children)) {
metadata.children.forEach(function (child) {
snapshot(child.id, dest);
});
}
dest.push(require.cache[path]);
return dest;
}
function restore(module) {
if (Array.isArray(module)) {
module.forEach(restore);
return;
}
require.cache[module.id] = module;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment