1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.runScript = void 0;
|
4 | /**
|
5 | * Use it in your top-level scripts like this:
|
6 | *
|
7 | * runScript(async () => {
|
8 | * await lalala()
|
9 | * // my script goes on....
|
10 | * })
|
11 | *
|
12 | * Advantages:
|
13 | * - Works kind of like top-level await
|
14 | * - No need to add `void`
|
15 | * - No need to add `.then(() => process.exit()` (e.g to close DB connections)
|
16 | * - No need to add `.catch(err => { console.error(err); process.exit(1) })`
|
17 | *
|
18 | * This function is kept light, dependency-free, exported separately.
|
19 | */
|
20 | function runScript(fn, opt = {}) {
|
21 | process.on('uncaughtException', err => {
|
22 | console.error('uncaughtException', err);
|
23 | });
|
24 | process.on('unhandledRejection', err => {
|
25 | console.error('unhandledRejection', err);
|
26 | });
|
27 | void (async () => {
|
28 | try {
|
29 | await fn();
|
30 | if (!opt.noExit) {
|
31 | setImmediate(() => process.exit(0));
|
32 | }
|
33 | }
|
34 | catch (err) {
|
35 | console.error('runScript failed:', err);
|
36 | process.exitCode = 1;
|
37 | if (!opt.noExit) {
|
38 | setImmediate(() => process.exit(1));
|
39 | }
|
40 | }
|
41 | })();
|
42 | }
|
43 | exports.runScript = runScript;
|