UNPKG

1.88 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.runScript = void 0;
4const { DEBUG_RUN_SCRIPT } = process.env;
5/**
6 * Use it in your top-level scripts like this:
7 *
8 * runScript(async () => {
9 * await lalala()
10 * // my script goes on....
11 * })
12 *
13 * Advantages:
14 * - Works kind of like top-level await
15 * - No need to add `void`
16 * - No need to add `.then(() => process.exit()` (e.g to close DB connections)
17 * - No need to add `.catch(err => { console.error(err); process.exit(1) })`
18 *
19 * This function is kept light, dependency-free, exported separately.
20 *
21 * Set env DEBUG_RUN_SCRIPT for extra debugging.
22 */
23function runScript(fn, opt = {}) {
24 const { logger = console, noExit } = opt;
25 process.on('uncaughtException', err => {
26 logger.error('uncaughtException:', err);
27 });
28 process.on('unhandledRejection', err => {
29 logger.error('unhandledRejection:', err);
30 });
31 if (DEBUG_RUN_SCRIPT) {
32 process.on('exit', code => logger.log(`process.exit event, code=${code}`));
33 process.on('beforeExit', code => logger.log(`process.beforeExit event, code=${code}`));
34 }
35 // fake timeout, to ensure node.js process won't exit until runScript main promise is resolved
36 const timeout = setTimeout(() => { }, 10000000);
37 void (async () => {
38 try {
39 await fn();
40 if (DEBUG_RUN_SCRIPT)
41 logger.log(`runScript promise resolved`);
42 if (!noExit) {
43 setImmediate(() => process.exit(0));
44 }
45 }
46 catch (err) {
47 logger.error('runScript error:', err);
48 process.exitCode = 1;
49 if (!noExit) {
50 setImmediate(() => process.exit(1));
51 }
52 }
53 finally {
54 clearTimeout(timeout);
55 }
56 })();
57}
58exports.runScript = runScript;