Server module hot update
fibjs
The 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.js
http handlerapp.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.js
direct reference web.js
, every time the application is updated, it must be restarted . Is there a way to automatically load the latest app.js
while updating the code ?app.js
web.js
We can use fibjs's nativeSandBoxmodule to achieve smooth hot updates. Make app.js
some 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.js
A cycle is started in , and a safe module is regenerated from the content require
every 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.js
svr
handler
web.js