NodeJS代码热更新

xiaoxiao2021-02-27  367

最近开发游戏项目,游戏服务器采用nodejs编写实现。 因此,经过在网上查询,通过实验后,确实了一种有效的热更新方法。 nodejs热更新的原理网上已经有说明,主要是清除module cache和重新加载模块。 首先建立一个测试程序,起名为HotPatchTest.js,代码很简单,就是打印一行命令:

console.log("This is a hotpatch test!");

然后建立真正的热更新程序,起名为HotPatch.js,代码如下:

var fs = require("fs"); //文件系统模块 function cleanCache(modulePath) { var module = require.cache[modulePath]; if (!module) { return; } if (module.parent) { module.parent.children.splice(module.parent.children.indexOf(module), 1); } require.cache[modulePath] = null; } var watchFile = function (filepath) { var fullpath = require.resolve(filepath); fs.watch(fullpath,function(event,filename){ if (event === "change") { cleanCache(fullpath); try { var routes = require(filepath); console.log("reload module",filename); } catch (ex) { console.error('module update failed'); } } }); }; var g_WatchFiles = ["./HotPatchTest"]; for (var i=0;i<g_WatchFiles.length;i++) { watchFile(g_WatchFiles[i]); } setInterval(function() { var hotPatchTest = require("./HotPatchTest"); }, 1000); 注意,需要热更新的文档,需要在每次调用的时候进行require,这样就可以在热加载完代码后利用更换好的模块了。
转载请注明原文地址: https://www.6miu.com/read-1873.html

最新回复(0)