UNPKG

2.43 kBMarkdownView Raw
1# signal-exit
2
3When you want to fire an event no matter how a process exits:
4
5- reaching the end of execution.
6- explicitly having `process.exit(code)` called.
7- having `process.kill(pid, sig)` called.
8- receiving a fatal signal from outside the process
9
10Use `signal-exit`.
11
12```js
13// Hybrid module, either works
14import { onExit } from 'signal-exit'
15// or:
16// const { onExit } = require('signal-exit')
17
18onExit((code, signal) => {
19 console.log('process exited!', code, signal)
20})
21```
22
23## API
24
25`remove = onExit((code, signal) => {}, options)`
26
27The return value of the function is a function that will remove
28the handler.
29
30Note that the function _only_ fires for signals if the signal
31would cause the process to exit. That is, there are no other
32listeners, and it is a fatal signal.
33
34If the global `process` object is not suitable for this purpose
35(ie, it's unset, or doesn't have an `emit` method, etc.) then the
36`onExit` function is a no-op that returns a no-op `remove` method.
37
38### Options
39
40- `alwaysLast`: Run this handler after any other signal or exit
41 handlers. This causes `process.emit` to be monkeypatched.
42
43### Capturing Signal Exits
44
45If the handler returns an exact boolean `true`, and the exit is a
46due to signal, then the signal will be considered handled, and
47will _not_ trigger a synthetic `process.kill(process.pid,
48signal)` after firing the `onExit` handlers.
49
50In this case, it your responsibility as the caller to exit with a
51signal (for example, by calling `process.kill()`) if you wish to
52preserve the same exit status that would otherwise have occurred.
53If you do not, then the process will likely exit gracefully with
54status 0 at some point, assuming that no other terminating signal
55or other exit trigger occurs.
56
57Prior to calling handlers, the `onExit` machinery is unloaded, so
58any subsequent exits or signals will not be handled, even if the
59signal is captured and the exit is thus prevented.
60
61Note that numeric code exits may indicate that the process is
62already committed to exiting, for example due to a fatal
63exception or unhandled promise rejection, and so there is no way to
64prevent it safely.
65
66### Browser Fallback
67
68The `'signal-exit/browser'` module is the same fallback shim that
69just doesn't do anything, but presents the same function
70interface.
71
72Patches welcome to add something that hooks onto
73`window.onbeforeunload` or similar, but it might just not be a
74thing that makes sense there.