UNPKG

2.5 kBJavaScriptView Raw
1var parent = module.parent;
2//replace ALL of our paths with the parents ones (disabling this hack for now)
3//module.paths.splice.apply(module.paths, [0, module.paths.length].concat(parent.paths));
4//module.filename = parent.filename;
5
6function reloadCtx(require, name) {
7 var id = require.resolve(name),
8 oldCache = require.cache[id];
9 delete require.cache[id];
10 try {
11 return require(id);
12 } catch (e) {
13 if (oldCache !== undefined) {
14 require.cache[id] = oldCache; //restore the old cache since the new failed
15 }
16 throw e;
17 }
18 return null;
19}
20
21//fallback in case module.filename override doesn't work
22//see what _resolveLookupPaths is doing in nodejs/lib/module.js
23function reloadParent(name) {
24 var ctx = parent.constructor,
25 id = ctx._resolveFilename(name, parent),
26 oldCache = ctx._cache[id];
27 delete ctx._cache[id];
28 try {
29 return parent.require(id);
30 } catch (e) {
31 if (oldCache !== undefined) {
32 ctx._cache[id] = oldCache; //restore the old cache since the new failed
33 }
34 throw e;
35 }
36 return null;
37}
38
39function reload(name, ctx) {
40 //detect if they did require('require-reload')(require)
41 if (typeof name === 'function' && typeof name.cache === 'object') {
42 var func = reloadCtx.bind(null, name);
43 func.resolve = name.resolve;
44 func.emptyCache = function() {
45 for (var id in name.cache) {
46 delete name.cache[id];
47 }
48 };
49 return func;
50 }
51 if (ctx !== undefined) {
52 return reloadCtx(ctx, name);
53 }
54 if (module.filename === undefined) {
55 throw new Error("Cannot override module.filename since it isn't used anymore. Please upgrade require-reload!");
56 }
57 //no context means we must fallback to one of these hacks
58 //return reloadCtx(require, name); //this only works if we hacked the filename at the top
59 return reloadParent(name);
60}
61
62reload.resolve = function(req, context) {
63 if (context !== undefined) {
64 return context.resolve(req);
65 }
66 return parent.constructor._resolveFilename(req, parent);
67};
68reload.emptyCache = function(context) {
69 var cache = context ? context.cache : parent.constructor._cache;
70 for (var id in cache) {
71 delete cache[id];
72 }
73};
74module.exports = reload;
75
76//don't allow reload.js to be cached otherwise we can't use the hack with the parent filename
77delete require.cache[module.id];