-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathechoServer.js
More file actions
70 lines (60 loc) · 1.96 KB
/
echoServer.js
File metadata and controls
70 lines (60 loc) · 1.96 KB
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
// This is a template script created for some testing
// This is not the actual transformer server
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
const url = require("url");
require("./util/logUtil");
function start(port) {
if (!port) {
port = 9292;
}
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Main server body
http
.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
// Adding logic for a call that will invalidate cache
// for particular module in order that next require call for
// that module will reload the same
if (request.method == "POST") {
var body = "";
var respBody = "";
request.on("data", function(data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e8) request.connection.destroy();
});
request.on("end", async function() {
try {
// need to send 400 error for malformed JSON
console.log(body);
response.statusCode = 200;
response.end(body);
} catch (se) {
response.statusCode = 500; // 500 for other errors
response.statusMessage = se.message;
console.log(se.stack);
response.end();
}
});
} else {
console.log(url.parse(request.url, true).query);
}
})
.listen(port);
console.log(`Worker ${process.pid} started`);
}
console.log("echoServer: started");
}
start(9292);