-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
53 lines (46 loc) · 1.22 KB
/
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
/* eslint-disable no-console */
/* eslint-disable no-plusplus */
const cluster = require('cluster')
const os = require('os')
const app = require('./app')
require('dotenv').config()
let server
const exitHandler = () => {
if (server) {
server.close(() => {
console.info('Server closed')
process.exit(1)
})
} else {
process.exit(1)
}
}
const unexpectedErrorHandler = (error) => {
console.error(error)
exitHandler()
}
process.on('uncaughtException', unexpectedErrorHandler)
process.on('unhandledRejection', unexpectedErrorHandler)
process.on('SIGTERM', () => {
console.info('SIGTERM received')
if (server) {
server.close()
}
})
if (process.env.CLUSTER_MODE === 'on' && cluster.isMaster) {
const cpuCore = os.cpus().length;
for (let i = 0; i < cpuCore; i++) {
cluster.fork();
}
cluster.on('online', (worker) => {
if (worker.isConnected()) console.info(`worker is active ${worker.process.pid}`);
})
cluster.on('exit', (worker) => {
if (worker.isDead()) console.info(`worker is dead ${worker.process.pid}`);
cluster.fork();
})
} else {
app.listen(process.env.APP_PORT, () => {
console.info(`express boillerplate app running in port ${process.env.APP_PORT}`)
})
}