// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the
// filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.
// Then have it load the file contents before returning its exports
// object.
Module._load = function(request, parent, isMain) {
var filename = Module._resolveFilename(request, parent);
var cachedModule = Module._cache[filename];
if (cachedModule) {
return cachedModule.exports;
}
var module = new Module(filename, parent);
Module._cache[filename] = module;
module.load(filename);
return module.exports;
};
require.cache = Module._cache;
可以發現其中的核心就是 Module._cache ,只要清除了這個模塊緩存,下一次 require 的時候,模塊管理器就會重新加載最新的代碼了。
寫一個小程序驗證一下:
// main.js
function cleanCache (module) {
var path = require.resolve(module);
require.cache[path] = null;
}
setInterval(function () {
cleanCache(\\\’./code.js\\\’);
var code = require(\\\’./code.js\\\’);
console.log(code);
}, 5000);
// code.js
module.exports = \\\’hello world\\\’;
我們執行一下 main.js ,同時取修改 code.js 的內容,就可以發現控制臺中,我們代碼成功的更新為了最新的代碼。
那么模塊管理器更新代碼的問題已經解決了,接下來再看看在 Web 應用中,我們如何讓新的模塊可以被實際執行。