UNPKG

2.02 kBPlain TextView Raw
1import type { CommonLogger } from '@naturalcycles/js-lib'
2
3export interface RunScriptOptions {
4 /**
5 * @default false
6 * Set to true to NOT call process.exit(0) after function is completed.
7 * Currently it exists because of `jest --maxWorkers=1` behavior. To be investigated more..
8 */
9 noExit?: boolean
10
11 /**
12 * Default to `console`
13 */
14 logger?: CommonLogger
15}
16
17const { DEBUG_RUN_SCRIPT } = process.env
18
19/**
20 * Use it in your top-level scripts like this:
21 *
22 * runScript(async () => {
23 * await lalala()
24 * // my script goes on....
25 * })
26 *
27 * Advantages:
28 * - Works kind of like top-level await
29 * - No need to add `void`
30 * - No need to add `.then(() => process.exit()` (e.g to close DB connections)
31 * - No need to add `.catch(err => { console.error(err); process.exit(1) })`
32 *
33 * This function is kept light, dependency-free, exported separately.
34 *
35 * Set env DEBUG_RUN_SCRIPT for extra debugging.
36 */
37export function runScript(fn: (...args: any[]) => any, opt: RunScriptOptions = {}): void {
38 const { logger = console, noExit } = opt
39
40 process.on('uncaughtException', err => {
41 logger.error('uncaughtException:', err)
42 })
43 process.on('unhandledRejection', err => {
44 logger.error('unhandledRejection:', err)
45 })
46
47 if (DEBUG_RUN_SCRIPT) {
48 process.on('exit', code => logger.log(`process.exit event, code=${code}`))
49 process.on('beforeExit', code => logger.log(`process.beforeExit event, code=${code}`))
50 }
51
52 // fake timeout, to ensure node.js process won't exit until runScript main promise is resolved
53 const timeout = setTimeout(() => {}, 10000000)
54
55 void (async () => {
56 try {
57 await fn()
58
59 if (DEBUG_RUN_SCRIPT) logger.log(`runScript promise resolved`)
60
61 if (!noExit) {
62 setImmediate(() => process.exit(0))
63 }
64 } catch (err) {
65 logger.error('runScript error:', err)
66 process.exitCode = 1
67 if (!noExit) {
68 setImmediate(() => process.exit(1))
69 }
70 } finally {
71 clearTimeout(timeout)
72 }
73 })()
74}