How to use the exit function from process

Find comprehensive JavaScript process.exit code examples handpicked from public code repositorys.

131
132
133
134
135
136
137
138
139
140
                STEALTH.kill('SIGTERM');
                STEALTH = null;
        }

        app.quit();
        process.exit(0);

});

app.whenReady().then(() => {
fork icon147
star icon904
watch icon37

+ 15 other calls in file

99
100
101
102
103
104
105
  } catch (err) {
    await logger.error(err);
  }

  if (parentPort) parentPort.postMessage('done');
  else process.exit(0);
})();
fork icon70
star icon548
watch icon8

198
199
200
201
202
203
204
205
206
207
208
209
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }


  console.log(red, ' Test demo did not start successfully');
  terminateTestDemo();
  exit(1);
};


const startTesting = () => {
  console.log(green, ' Running test');
fork icon149
star icon230
watch icon0

+ 14 other calls in file

9
10
11
12
13
14
15
16
17
18
  await page.goto(args[0], {waitUntil : 'networkidle0'});
  console.log(await page.content());
} 
catch(e) {
  console.log(e)
  process.exit()
}
finally {
  browser.close()
}
fork icon31
star icon64
watch icon6

18
19
20
21
22
23
24
25
26
27
function run() {
  const args = process.argv.slice(2);

  if (args.length === 0 || (!args[0] && !process.env.PUBLIC_DOMAIN)) {
    console.error(usage);
    process.exit(-1);
  }

  const publicDomain = args[0] || process.env.PUBLIC_DOMAIN;
  updateManifests(publicDomain);
fork icon1
star icon8
watch icon3

49
50
51
52
53
54
55
56
57
58
// private property: `sdkInstance._tracerProvider`. An issue can be opened
// to discuss the exposure of a public getter with the OpenTelemetry developers.
//
// `beforeExit`
//
// If set, Apostrophe will invoke it (await) before invoking process.exit.
// `beforeExit` may be an async function, will be awaited, and takes no arguments.
//
// ## Awaiting the Apostrophe function
//
fork icon546
star icon0
watch icon126

+ 3 other calls in file

148
149
150
151
152
153
154
155
156
157
example, [`Promise.race()`][] can trigger a `'multipleResolves'` event.

```js
process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
fork icon372
star icon0
watch icon78

+ 15 other calls in file

6
7
8
9
10
11
12
13
14
15
const { setClientRebuildInProgress, setServerRebuildInProgress, generateBuildId, startAutoRefreshServer, initiateRefresh } = require("./scripts/startup/autoRefreshServer");
/**
 * This is used for clean exiting in Github workflows by the dev
 * only route /api/quit
 */
process.on("SIGQUIT", () => process.exit(0));

const [opts, args] = cliopts.parse(
  ["production", "Run in production mode"],
  ["settings", "A JSON config file for the server", "<file>"],
fork icon99
star icon456
watch icon14

197
198
199
200
201
202
203
204
205
206
      await options.beforeExit(code, message);
    } catch (e) {
      console.error('beforeExit handler error', e);
    }
  }
  process.exit(code);
};

try {
  const matches = process.version.match(/^v(\d+)/);
fork icon545
star icon0
watch icon125

+ 15 other calls in file

87
88
89
90
91
92
93
94
95
96
// 在进程关闭时,同时关闭数据采集
process.on('SIGTERM', () => {
  sdk.shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error) => console.log('Error terminating tracing', error))
    .finally(() => process.exit(0));
});

Bootstrap
  .configure(/**/)
fork icon503
star icon0
watch icon100

+ 3 other calls in file

122
123
124
125
126
127
128
129
130
                answer = prompt(cli.dim(`(tuspa): `))
        } while (!['u', 's', 't', 'a'].includes(answer))
}
if (answer === 'a') {
        console.log('Exiting...')
        exit(0)
} else if (answer === 's') {
        return skippedValues.push({ rule, msg: 'skipped' })
}
fork icon56
star icon126
watch icon7

58
59
60
61
62
63
64
65
66

if (current.build[0] === currentRev) {
    actions.setOutput('shouldPublish', false);

    console.log('No new commits since last publish. Exiting.');
    process.exit(0); // eslint-disable-line unicorn/no-process-exit

    return;
}
fork icon315
star icon0
watch icon59

+ 3 other calls in file

68
69
70
71
72
73
74
75
76
77
        arg = arg.join(' ');
        try { console.log(eval(arg)); }
        catch (e) { console.log(e); }
    },
    exit: function(arg) {
        process.exit();
    }
};
rl.on('line', (str) => {
    rl.pause();
fork icon217
star icon162
watch icon8

+ 3 other calls in file

69
70
71
72
73
74
75
76
77
78
                Context.logger.info(`Finished DART command-line mode pid: ${process.pid}, job: ${opts.job}. Exit Code: ${exitCode}`);
                process.exit(exitCode);
        } catch (err) {
                Context.logger.error(`Finished DART command-line mode pid ${process.pid} with error ${err}`);
                console.error(err);
                process.exit(Constants.EXIT_RUNTIME_ERROR);
        }
}

// This prevents a bug where y18n may wipe out locale files.
fork icon2
star icon39
watch icon10

+ 5 other calls in file

55
56
57
58
59
60
61
62
63
64
async function gracefulClusterShutdown () {
  console.log('Starting graceful cluster shutdown')
  shuttingDownServer = true
  await shutdownWorkers('SIGTERM')
  console.log('Successfully finished graceful cluster shutdown')
  process.exit(0)
}

/**
 * Shutdown all worker processes.
fork icon103
star icon0
watch icon27

7
8
9
10
11
12
13
14
15
16
        process.stdout.write("Usage:\n");
        process.stdout.write(`\tnode ${basename(__filename)} [--update] [--version MAJOR.MINOR.PATCH]\n\n`);

        process.stdout.write("\t--update\n\t\tExecute the script and applies the update. Without this parameter, the scripts runs a dry-test only.\n");
        process.stdout.write("\t--version MAJOR.MINOR.PATCH\n\t\tLook for the specified version only\n");
        exit();
}

let applyUpdate = false;
let specificVersion = undefined;
fork icon6
star icon46
watch icon3

23
24
25
26
27
28
29
30
31
32
const network: string = process.argv[3]

const netconfig = config.networks[network]
if (config === undefined) {
  console.log('Unsupported network: ' + network)
  exit(1)
}

const algodClient = new algosdk.Algodv2(netconfig.token, netconfig.api, netconfig.port)
const pclib = new PricecasterLib(algodClient, '4NM56GAFQEXSEVZCLAUA6WXFGTRD6ZCEGNLGT2LGLY25CHA6RLGHQLPJVM')
fork icon1
star icon0
watch icon6

+ 3 other calls in file

88
89
90
91
92
93
94
95
96
97
});

electronProcess.on('close', (code) => {
        logger.log(`Electron Process closed. Exited with code ${code}`);
        // Server shouldn't shut down on exit because electron restart closes down electron and restarts in the background.
        // process.exit();
});

process.on('exit', () => {
        // Server shouldn't shut down on exit because electron restart closes down electron and restarts in the background.
fork icon1
star icon11
watch icon9

+ 3 other calls in file

418
419
420
421
422
423
424
425
426
427
> 防御性编程是一种编程习惯,是指预见在什么地方可能会出现问题,然后创建一个环境来测试错误,当预见的问题出现的时候通知你,并执行一个你指定的损害控制动作

### uncaughtException

> 当异常没有被捕获一路冒泡到 Event Loop 时就会触发该事件 process 对象上的 `uncaughtException` 事件. 默认情况下, Node.js 对于此类异常会直接将其堆栈跟踪信息输出给 `stderr` 并结束进程, 而为 `uncaughtException` 事件添加监听可以覆盖该默认行为, 不会直接结束进程  
> `uncaughtException` 的初衷是可以让你拿到错误之后可以做一些回收处理之后再 process.exit

```js
process.on('uncaughtException', err => {
  console.log(`Caught exception: ${err}`);
fork icon0
star icon16
watch icon2

+ 3 other calls in file

204
205
206
207
208
209
210
211
212
213
console.log('Machines:', machines.map(machine => machine.name).join(', '));
console.log();

try {
    let success = !!(await command());
    process.exit(!success);
} catch (err) {
    console.error(err);
    process.exit(1);
}
fork icon7
star icon35
watch icon0

+ 3 other calls in file