-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.ts
91 lines (78 loc) · 2.35 KB
/
main.ts
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
import {deduplicate} from '@alwatr/dedupe';
import {packageTracer} from '@alwatr/package-tracer';
packageTracer.add(__package_name__, __package_version__);
deduplicate({name: __package_name__});
/**
* Array of callback functions to be called when the process is exiting.
*/
const callbacks: (() => void)[] = [];
/**
* True whether the process is exiting to prevent calling the callbacks more than once.
*/
let exiting = false;
/**
* Add a callback function to be called when the process is exiting.
*
* @param callback The callback function to be called when the process is exiting.
*
* @example
* ```typescript
* const saveAllData = () => {
* // save all data
* };
*
* existHook(saveAllData);
* ```
*/
export function exitHook(callback: () => void): void {
callbacks.push(callback);
}
/**
* A once callback to be called on process exit event.
*/
function onExit_(signal: number | 'SIGINT' | 'SIGTERM') {
console.log('onExit({signal: %s})', signal);
if (exiting === true) return;
exiting = true;
for (const callback of callbacks) {
try {
callback();
}
catch (error) {
console.error('Error in exit hook callback:', error);
}
}
if (signal === 'SIGINT' || signal === 'SIGTERM') {
setTimeout(() => {
process.exit(0);
});
}
}
/**
* This event emitted when Node.js empties its event loop and has no additional work to schedule.
* Normally, the Node.js process will exit when there is no work scheduled,
* but a listener registered on the 'beforeExit' event can make **asynchronous calls**, and thereby cause the Node.js process to continue.
*
* @see https://nodejs.org/api/process.html#event-beforeexit
*/
// process.once('beforeExit', onExit_);
/**
* This event is emitted when the Node.js process is about to exit as a result of either:
* 1- The `process.exit()` method being called explicitly.
* 2- The Node.js event loop no longer having any additional work to perform.
*
* @see https://nodejs.org/api/process.html#event-exit
*/
process.once('exit', onExit_);
/**
* This event is emitted in terminal mode before exiting with code 128 + signal number.
*
* @see https://nodejs.org/api/process.html#signal-events
*/
process.once('SIGTERM', onExit_);
/**
* This event is emitted when `Ctrl+C` is pressed.
*
* @see https://nodejs.org/api/process.htm l#signal-events
*/
process.once('SIGINT', onExit_);