forked from sindresorhus/import-fresh
/
index.js
63 lines (55 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict';
var path = require('path');
var resolveFrom = require('resolve-from');
var callerPath = require('caller-path');
/**
* Removes a module from the cache
*/
require.uncache = function (moduleName) {
// Run over the cache looking for the files
// loaded by the specified module name
require.searchCache(moduleName, function (mod) {
delete require.cache[mod.id];
});
// Remove cached paths to the module.
// Thanks to @bentael for pointing this out.
Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
if (cacheKey.indexOf(moduleName)>0) {
delete module.constructor._pathCache[cacheKey];
}
});
};
/**
* Runs over the cache to search for all the cached
* files
*/
require.searchCache = function (moduleName, callback) {
// Resolve the module identified by the specified name
var mod = require.resolve(moduleName);
// Check if the module has been resolved and found within
// the cache
if (mod && ((mod = require.cache[mod]) !== undefined)) {
// Recursively go over the results
(function run(mod) {
// Go over each of the module's children and
// run over it
mod.children.forEach(function (child) {
run(child);
});
// Call the specified callback providing the
// found module
callback(mod);
})(mod);
}
};
module.exports = function (moduleId) {
if (typeof moduleId !== 'string') {
throw new TypeError('Expected a string');
}
var filePath = resolveFrom(path.dirname(callerPath()), moduleId);
var tmp = require.cache[filePath];
require.uncache(filePath);
var ret = require(filePath);
require.cache[filePath] = tmp;
return ret;
};