UNPKG

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