-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodeHandler.js
98 lines (83 loc) · 2.73 KB
/
nodeHandler.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
/*
This module handle the node starting and destruction.
*/
const options = require("./options");
const c = require("node:child_process");
class NodeHandler {
constructor() {
this.processPath = options.argv.command;
this.args = options.argv.arguments;
this.process = null;
this.askRestart = false; // Set to true when restarting the process.
this.restartInterval = null; // The restart interval loop, wait until the process stop running.
}
/*
Starting the node program.
*/
start() {
// Stopping the process if its already running.
if (this.askRestart && this.restartInterval) {
return;
} else if (this.isRunning()) {
this.stop();
}
console.log(`Starting ${this.processPath}!`);
// If the process fail to start, it mean the command does not exists
// or the arguments are not valid.
this.process = c.spawn(this.processPath, this.args);
// If the process fail to start, stop the program.
this.process.on("error", err => {
console.log(`Failed to start ${this.processPath}.`);
process.exit(-1);
});
const output = data => {
console.log(`${data}`);
}
this.process.stdout.on("data", output);
this.process.stderr.on("data", output);
this.process.on("close", () => {
console.log(`Process ${this.processPath} closed!`);
this.process = null;
});
}
/*
Stopping the node program.
*/
stop() {
if (this.isRunning() && !this.askRestart && !this.restartInterval) {
this.process.kill();
this.process = null; // Workaround: sometimes, a process do not have a return code.
}
}
/*
Helper function to restart node.
*/
restart() {
if (this.isRunning() || !this.process) {
// Send a signal to close the process.
if (this.isRunning()) {
this.process.kill();
this.askRestart = true;
}
this.restartInterval = setInterval(() => {
if (!this.isRunning()) {
// When the process stop running, stop waiting and restart a new instance.
clearInterval(this.restartInterval);
this.restartInterval = null;
this.process = null;
this.askRestart = false;
this.start();
}
}, 150);
}
}
/*
Indicate if the process is running.
*/
isRunning() {
return this.process && this.process.exitCode === null;
}
}
module.exports = function() {
return new NodeHandler();
}