-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
92 lines (74 loc) · 2.01 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
const handlers = {}
, last = []
let finished = false
export default prexit
function prexit(signals, fn) {
if (typeof signals === 'function') {
fn = signals
signals = prexit.signals
}
let called = false
;['prexit'].concat(signals).forEach(signal => handle(signal, function(signal, error) {
if (called)
return
called = true
return fn(signal, error)
}))
}
prexit.signals = ['exit', 'beforeExit', 'uncaughtException', 'unhandledRejection', 'SIGTSTP', 'SIGQUIT', 'SIGHUP', 'SIGTERM', 'SIGINT']
prexit.logExceptions = true
prexit.exiting = false
prexit.last = addLast
prexit.exit = exit
prexit.ondone = ondone
function addLast(fn) {
last.length || prexit(() => {})
last.push(fn)
}
function exit(signal, code, error) {
if (typeof signal === 'number') {
error = code
code = signal
signal = 'prexit'
}
code && (process.exitCode = code)
Object.keys(handlers).length
? process.emit('prexit', error)
: process.exit()
}
function ondone(signal, error) {
process.exit() // eslint-disable-line
}
function handle(signal, fn) {
const handler = handlers[signal]
if (handler)
return handler.push(fn)
const fns = handlers[signal] = [fn]
process.on(signal, async function(error) {
prexit.exiting = true
error === signal && (error = null)
if ((signal === 'uncaughtException' || signal === 'unhandledRejection') && prexit.logExceptions)
console.error(error) // eslint-disable-line
try {
const xs = fns.map(fn => fn(signal, error)).filter(x => x && typeof x.then === 'function')
xs.length && await Promise.all(xs)
} catch (error) {
process.exitCode || (process.exitCode = 1)
prexit.logExceptions && console.error(error) // eslint-disable-line
}
done(signal, error)
})
}
function done(signal, error) {
if (finished)
return
finished = true
try {
last.forEach(fn => fn(signal))
} catch (err) {
error
? console.error(err) // eslint-disable-line
: error = err
}
prexit.ondone(signal, error)
}