-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (54 loc) · 1.85 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
/**
* @author TMJP ENGINEERING
* @copyright 2017
* reference http://stackoverflow.com/questions/18692536/node-js-server-close-event-doesnt-appear-to-fire
* , http://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits
* http://joseoncode.com/2014/07/21/graceful-shutdown-in-node-dot-js/
*/
module.exports = ProcessEndHandler();
function ProcessEndHandler() {
var callbacks = [];
var service = {
include: include,
};
initialize();
return service;
function include(callback) {
// push first the callback and wait for end process
callbacks.push(callback);
}
function runCallbacks(err) {
for (var key in callbacks) {
callbacks[key](err);
}
}
function initialize() {
// since we only want to run the call back once on any event that triggers
let check = 0;
// prevent the app to close instantly
process.stdin.resume();
// listen for close processes
// on ctrl + c
process.on('SIGINT', onEnd);
// on app close
process.on('exit', onEnd);
// on uncaught exceptions
process.on('uncaughtException', onEnd)
// on process terminated/kill
process.on('SIGTERM', onEnd);
/**
* if uncaught exception error has a value
*/
function onEnd(err) {
if (check) return;
// if it is not yet run increment the checker to inform that this was already run
check++;
// run process before closing
console.log('Before process end, running all registered callbacks');
runCallbacks(err);
console.log('All registered callbacks have been run, process will now end ...');
// inform to continue to exit
process.exit(0);
}
}
}