-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (87 loc) · 2.72 KB
/
index.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
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const getTransaction = require("./getTransaction");
const cluster = require("cluster");
let workers = [];
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const setupWorkerProcesses = () => {
// to read number of cores on system
let numCores = require("os").cpus().length;
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());
// to 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());
// to receive messages from worker process
workers[workers.length - 1].on("message", function(message) {
console.log(message);
});
});
};
const setUpExpress = () => {
app.get("/eth/api/v1/transaction/:id", async (req, res) => {
try {
const tx = req.params.id;
const result = await getTransaction(tx);
res.status(200).send({
result,
error: null
});
} catch (err) {
res.status(404).send({
result: null,
error: err.message
});
}
});
process
.on("unhandledRejection", (reason, p) => {
console.error(reason, "Unhandled Rejection at Promise", p);
})
.on("uncaughtException", err => {
console.error(err, "Uncaught Exception thrown");
//process.exit(1);
});
const port = 5000;
app.listen(port, () => {
console.log("node server running at ", port);
});
};
const setupServer = isClusterRequired => {
// if it is a master process then call setting up worker process
if (isClusterRequired && cluster.isMaster) {
setupWorkerProcesses();
} else {
// to setup server configurations and share port address for incoming requests
setUpExpress();
}
};
setupServer(true);