-
Notifications
You must be signed in to change notification settings - Fork 77
/
external-server.js
105 lines (88 loc) · 2.21 KB
/
external-server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const net = require("net");
const fs = require("fs");
const bundlePath = "./var/webpack/";
const bundleFileName = "server-bundle.js";
const unixSocketPath = "var/node.sock";
let currentArg;
class Handler {
constructor() {
this.queue = [];
this.initialized = false;
}
handle(connection) {
const callback = () => {
connection.setEncoding("utf8");
let data = [];
let lastChar;
connection.on("data", chunk => {
data.push(chunk);
lastChar = chunk.substr(chunk.length - 1);
if (lastChar === "\0") {
data = data.join("");
let result = eval(data.slice(0, -1));
connection.write(result);
console.log("Request processed");
connection.end();
}
});
};
if (this.initialized) {
callback();
} else {
this.queue.push(callback);
}
}
initialize() {
console.log("Processing " + this.queue.length + " pending requests");
var callback = this.queue.pop();
while (callback) {
callback();
callback = this.queue.pop();
}
this.initialized = true;
}
}
var handler = new Handler();
process.argv.forEach(val => {
if (val[0] == "-") {
currentArg = val.slice(1);
return;
}
if (currentArg == "s") {
bundleFileName = val;
}
});
try {
fs.mkdirSync(bundlePath);
} catch (e) {
if (e.code != "EEXIST") throw e;
}
require(bundlePath + bundleFileName);
console.log("Loaded server bundle: " + bundlePath + bundleFileName);
handler.initialize();
fs.watchFile(bundlePath + bundleFileName, curr => {
if (curr && curr.blocks && curr.blocks > 0) {
if (handler.initialized) {
console.log(
"Reloading server bundle must be implemented by restarting the node process!"
);
return;
}
require(bundlePath + bundleFileName);
console.log("Loaded server bundle: " + bundlePath + bundleFileName);
handler.initialize();
}
});
fs.stat(unixSocketPath, function(err) {
if (!err) {
fs.unlinkSync(unixSocketPath);
}
var unixServer = net.createServer(function(connection) {
handler.handle(connection);
});
unixServer.listen(unixSocketPath);
process.on("SIGINT", () => {
unixServer.close();
process.exit();
});
});