-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathexit.ts
41 lines (33 loc) · 1.01 KB
/
exit.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
import { Logger } from './logger';
type cleanUpFn = () => void;
const cleanUpHandlers: cleanUpFn[] = [];
export function registerExitCleanUp(fn) {
cleanUpHandlers.push(fn);
}
export class ExitManager {
constructor(private log: Logger) {
process.stdin.resume(); //so the program will not close instantly
//do something when app is closing
process.on('exit', this.exitHandler.bind(this));
//catches ctrl+c event
process.on('SIGINT', this.exitHandler.bind(this));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', this.exitHandler.bind(this));
process.on('SIGUSR2', this.exitHandler.bind(this));
//catches uncaught exceptions
process.on('uncaughtException', this.exitHandler.bind(this));
}
exitHandler(options, err) {
for (const fn of cleanUpHandlers) {
try {
fn();
} catch (err) {
this.log.info('Failed to call cleanup function ' + err);
}
}
if (err) {
this.log.info(err);
}
process.exit();
}
}