decache.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var path = require('path'); // if module is locally defined we path.resolve it
  2. var callsite = require('callsite');
  3. require.find = function (moduleName) {
  4. if (moduleName[0] === '.') {
  5. var stack = callsite();
  6. for (var i in stack) {
  7. var filename = stack[i].getFileName();
  8. if (filename !== module.filename) {
  9. moduleName = path.resolve(path.dirname(filename), moduleName);
  10. break;
  11. }
  12. }
  13. }
  14. try {
  15. return require.resolve(moduleName);
  16. } catch (e) {
  17. return;
  18. }
  19. };
  20. /**
  21. * Removes a module from the cache. We need this to re-load our http_request !
  22. * see: https://stackoverflow.com/a/14801711/1148249
  23. */
  24. require.decache = function (moduleName) {
  25. moduleName = require.find(moduleName);
  26. if(!moduleName) { return; }
  27. // Run over the cache looking for the files
  28. // loaded by the specified module name
  29. require.searchCache(moduleName, function (mod) {
  30. delete require.cache[mod.id];
  31. });
  32. // Remove cached paths to the module.
  33. // Thanks to @bentael for pointing this out.
  34. Object.keys(module.constructor._pathCache).forEach(function (cacheKey) {
  35. if (cacheKey.indexOf(moduleName) > -1) {
  36. delete module.constructor._pathCache[cacheKey];
  37. }
  38. });
  39. };
  40. /**
  41. * Runs over the cache to search for all the cached
  42. * files
  43. */
  44. require.searchCache = function (moduleName, callback) {
  45. // Resolve the module identified by the specified name
  46. var mod = require.resolve(moduleName);
  47. var visited = {};
  48. // Check if the module has been resolved and found within
  49. // the cache no else so #ignore else https://git.io/vtgMI
  50. /* istanbul ignore else */
  51. if (mod && ((mod = require.cache[mod]) !== undefined)) {
  52. // Recursively go over the results
  53. (function run(current) {
  54. visited[current.id] = true;
  55. // Go over each of the module's children and
  56. // run over it
  57. current.children.forEach(function (child) {
  58. // ignore .node files, decachine native modules throws a
  59. // "module did not self-register" error on second require
  60. if (path.extname(child.filename) !== '.node' && !visited[child.id]) {
  61. run(child);
  62. }
  63. });
  64. // Call the specified callback providing the
  65. // found module
  66. callback(current);
  67. })(mod);
  68. }
  69. };
  70. module.exports = require.decache;
  71. module.exports.default = require.decache;