Skip to content

Instantly share code, notes, and snippets.

@vymarkov
Last active August 29, 2015 14:26
Show Gist options
  • Save vymarkov/de10fc82a5c8831c62c0 to your computer and use it in GitHub Desktop.
Save vymarkov/de10fc82a5c8831c62c0 to your computer and use it in GitHub Desktop.
clearCache
/*
clearCache();
clearCache('foo');
clearCache(path.resolve('foo'));
clearCache(['foo', 'bar']);
clearCache();
*/
clearCache: function clearCache(modules, removeChilds) {
modules = (modules === null || modules === undefined) && (arguments.length === 0) ? [require.main.filename] : modules;
modules = typeof modules === 'string' ? [modules] : modules;
modules = modules instanceof Array ? modules : [];
removeChilds = typeof removeChilds === 'boolean' ? removeChilds : false;
modules.filter(function(moduleId) {
return typeof moduleId === 'string' && moduleId !== '';
}).map(function(moduleId) {
return require.resolve(moduleId);
}).forEach(function(moduleId) {
if (moduleId in require.cache) {
if (removeChilds) {
require.cache[moduleId].children.forEach(function(module) {
clearCache(module.id);
});
}
if (require.main.filename !== moduleId) {
delete require.cache[moduleId];
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment