Guide Development Guide

Server module hot update

fibjsThe http server is a memory-resident independent server program, which means that when there is a version update, the service program often needs to be restarted.

Suppose we have the following service program:

  • web.jshttp handler
  • app.jsApplication 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, every time the application is updated, it must be restarted . Is there a way to automatically load the latest app.jswhile updating the code ?app.jsweb.js

We can use fibjs's nativeSandBoxmodule to achieve smooth hot updates. Make app.jssome changes to :

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); } // update svr.handler every 1 second. coroutine.start(function() { while (true) { coroutine.sleep(1000); svr.handler = new_web(); } }) var svr = new http.Server(8080, new_web()); svr.start();

app.jsA cycle is started in , and a safe module is regenerated from the content requireevery 1s for remounting . When the content in needs to be updated, just replace the file to achieve a smooth update of the server program.web.jssvrhandlerweb.js

👉【High Performance Web Application Practice