UNPKG

1.3 kBPlain TextView Raw
1export interface RunScriptOptions {
2 /**
3 * @default false
4 * Set to true to NOT call process.exit(0) after function is completed.
5 * Currently it exists because of `jest --maxWorkers=1` behavior. To be investigated more..
6 */
7 noExit?: boolean
8}
9
10/**
11 * Use it in your top-level scripts like this:
12 *
13 * runScript(async () => {
14 * await lalala()
15 * // my script goes on....
16 * })
17 *
18 * Advantages:
19 * - Works kind of like top-level await
20 * - No need to add `void`
21 * - No need to add `.then(() => process.exit()` (e.g to close DB connections)
22 * - No need to add `.catch(err => { console.error(err); process.exit(1) })`
23 *
24 * This function is kept light, dependency-free, exported separately.
25 */
26export function runScript(fn: (...args: any[]) => any, opt: RunScriptOptions = {}): void {
27 process.on('uncaughtException', err => {
28 console.error('uncaughtException', err)
29 })
30 process.on('unhandledRejection', err => {
31 console.error('unhandledRejection', err)
32 })
33
34 void (async () => {
35 try {
36 await fn()
37
38 if (!opt.noExit) {
39 setImmediate(() => process.exit(0))
40 }
41 } catch (err) {
42 console.error('runScript failed:', err)
43 process.exitCode = 1
44 if (!opt.noExit) {
45 setImmediate(() => process.exit(1))
46 }
47 }
48 })()
49}