nodejs 熱更新

gulp監控工具nodemon,能夠監視代碼的改動而重啓服務器,然而仍是以爲若不用重啓而直接加載新的代碼更方便,因此在網上找了下nodejs熱更新的方法,順便記錄一下node

 

其實,方法也是經過監視文件被改動的時候,將緩衝區中已加載的對應模塊清除,此時緩衝區中就不保留有該文件模塊的代碼,直至下一個請求該文件模塊到來時,纔會去從新加載一遍對應的模塊,而正是改動以後的文件模塊。gulp

而總結出來要解決的問題有以下三個:緩存

  • 如何更新模塊代碼
  • 如何使用新模塊處理請求
  • 如何釋放老模塊的資源

 

先看看node相關的源代碼:服務器

// Check the cache for the requested file.
// 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;

下面是熱更新的測試代碼:app

app.use('/', function(req, res, next){    //這裏的路由要這樣寫才能使得清除緩存後的下一次請求能從新加載模塊
  routes(req, res, next);
});
.
.
. fs.watch(require.resolve(
'./routes/index'), function () { cleanCache(require.resolve('./routes/index')); //清除該路徑模塊的緩存 try { routes = require('./routes/index'); } catch (ex) { console.error('module update failed'); } }); .
.
.
function cleanCache(modulePath) { var module = require.cache[modulePath]; // remove reference in module.parent if (module.parent) { module.parent.children.splice(module.parent.children.indexOf(module), 1); //釋放老模塊的資源 } require.cache[modulePath] = null; //緩存置空 }
相關文章
相關標籤/搜索