Guide Development Guide

Server module hot update

fibjs The http server is an independent server program that resides in memory, which means that the service program often needs to be restarted when there is a version update.

Suppose there is the following service program:

  • web.js http handler
  • app.js Application entrance
1 2 3 4 5 6
// web.js var _ver = new Date(); module.exports = function (r) { r.response.write("Hello, new word @ " + _ver); }
1 2 3 4 5 6 7 8 9
// app.js var http = require("http"); var vm = require("vm"); var coroutine = require("coroutine"); var webServer = require("./web"); var svr = new http.Server(8080, webServer); svr.start();

In app.jsdirect reference web.js, when each update applications, they both must be restarted app.js, there is no way you can simultaneously update the code, so that app.jsautomatically loads the latest web.jsit?

We can use fibjs's native SandBoxModule to achieve smooth hot update. To app.jsmake some changes:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// app.js var http = require("http"); var vm = require("vm"); var coroutine = require("coroutine"); // var webServer = require("./web"); function new_web() { return new vm.SandBox({ mq: require("mq") }).require("./web.js", __dirname); } // 每 1s 重新载入一遍 ./web.js 文件以更新 srv 的 handler coroutine.start(function() { while (true) { coroutine.sleep(1000); svr.handler = new_web(); } }) var svr = new http.Server(8080, new_web()); svr.start();

app.jsStart a cycle, every 1s again requirea web.jscontent generation security module for svrremounted handler. When web.jsthe time required to update the content, simply replace the file, you can achieve a smooth update server program.

👉 [ Domain Routing ]