-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.js
More file actions
49 lines (40 loc) · 1.13 KB
/
Copy pathserver.js
File metadata and controls
49 lines (40 loc) · 1.13 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
'use strict';
const http = require('http');
const os = require('os');
const cluster = require('cluster');
const port = process.env.PORT || 3000;
const cpus = os.cpus();
if (cluster.isMaster) {
console.log('Node version:', process.version);
console.log('CPU: %d x %s', cpus.length, cpus[0].model);
if (!process.env.CLUSTER) {
runServer();
} else {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < cpus.length; i++) {
cluster.fork();
}
}
console.log('Listening on port %s', port);
} else {
console.log(`Worker ${process.pid} started`);
runServer();
}
function runServer() {
let server = http.createServer((request, response) => {
const { headers, method, url } = request;
let body = [];
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = JSON.parse(Buffer.concat(body).toString());
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(body))
});
})
server.listen(port);
}