// 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 應用中,我們如何讓新的模塊可以被實際執行。

 更多關于云服務器域名注冊,虛擬主機的問題,請訪問三五互聯官網:www.shinetop.cn

贊(0)
聲明:本網站發布的內容(圖片、視頻和文字)以原創、轉載和分享網絡內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。郵箱:3140448839@qq.com。本站原創內容未經允許不得轉載,或轉載時需注明出處:三五互聯知識庫 » Node.js Web應用代碼熱更新的另類思路

登錄

找回密碼

注冊