-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
107 lines (93 loc) · 3.37 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
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
106
107
require('@babel/register');
/* eslint-disable no-console */
const chalk = require('chalk');
const dotenv = require('dotenv');
const cluster = require('cluster');
const numCores = require('os').cpus().length;
const app = require('./app');
// Handle uncaught exceptions
process.on('uncaughtException', (uncaughtExc) => {
// Won't execute
console.log(chalk.bgRed('UNCAUGHT EXCEPTION! 💥 Shutting down...'));
console.log('uncaughtException Err::', uncaughtExc);
console.log('uncaughtException Stack::', JSON.stringify(uncaughtExc.stack));
process.exit(1);
});
// Setup number of worker processes to share port which will be defined while setting up server
const workers = [];
const setupWorkerProcesses = () => {
// Read number of cores on system
console.log(`Master cluster setting up ${numCores} workers`);
// Iterate on number of cores need to be utilized by an application
// Current example will utilize all of them
for (let i = 0; i < numCores; i++) {
// Creating workers and pushing reference in an array
// these references can be used to receive messages from workers
workers.push(cluster.fork());
// Receive messages from worker process
workers[i].on('message', function (message) {
console.log(message);
});
}
// Process is clustered on a core and process id is assigned
cluster.on('online', function (worker) {
console.log(`Worker ${worker.process.pid} is listening`);
});
// If any of the worker process dies then start a new one by simply forking another one
cluster.on('exit', function (worker, code, signal) {
console.log(
`Worker ${worker.process.pid} died with code: ${code}, and signal: ${signal}`
);
console.log('Starting a new worker');
cluster.fork();
workers.push(cluster.fork());
// Receive messages from worker process
workers[workers.length - 1].on('message', function (message) {
console.log(message);
});
});
};
// Setup an express server and define port to listen all incoming requests for this application
const setUpExpress = () => {
dotenv.config({ path: '.env' });
const port = process.env.APP_PORT || 3000;
const server = app.listen(port, () => {
console.log(`App running on port ${chalk.greenBright(port)}...`);
});
// In case of an error
app.on('error', (appErr, appCtx) => {
console.error('app error', appErr.stack);
console.error('on url', appCtx.req.url);
console.error('with headers', appCtx.req.headers);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (err) => {
console.log(chalk.bgRed('UNHANDLED REJECTION! 💥 Shutting down...'));
console.log(err.name, err.message);
// Close server & exit process
server.close(() => {
process.exit(1);
});
});
process.on('SIGTERM', () => {
console.log('👋 SIGTERM RECEIVED. Shutting down gracefully');
server.close(() => {
console.log('💥 Process terminated!');
});
});
};
// Setup server either with clustering or without it
const setupServer = (isClusterRequired) => {
// If it is a master process then call setting up worker process
if (isClusterRequired && cluster.isMaster) {
setupWorkerProcesses();
} else {
// Setup server configurations and share port address for incoming requests
setUpExpress();
}
};
if (process.env.NODE_ENV === 'production') {
setupServer(true);
} else {
setupServer(false);
}