Guide Development Guide

Server module hot update

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

Suppose there is the following service program:

  • web.js http handler
  • app.js application entry
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.js direct reference web.js , when each update applications, they both must restart app.js , there is no way you can update the code at the same time, let app.js automatically load the latest web.js it?

We can achieve smooth hot updates through fibjs's native SandBox module. Make some changes to app.js :

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.js start of a cycle, every lS again require a web.js content generated security module for svr remounted handler . When the content in web.js needs to be updated, just replace the file to achieve smooth update of the server program.