CtrlNode.js に対して、 + C、例外、またはその他の理由など、何らかの理由で終了する直前に常に何かを実行するように指示します。
私はこれを試しました:
process.on('exit', function (){
console.log('Goodbye!');
});
プロセスを開始して終了しましたが、何も起こりませんでした。もう一度開始してCtrl+を押しましたCが、それでも何も起こりませんでした...
ベストアンサー1
アップデート:
`process.on('exit')` のハンドラーを登録し、それ以外の場合(`SIGINT` または未処理の例外) には `process.exit()` を呼び出すことができます。process.stdin.resume(); // so the program will not close instantly
function exitHandler(options, exitCode) {
if (options.cleanup) console.log('clean');
if (exitCode || exitCode === 0) console.log(exitCode);
if (options.exit) process.exit();
}
// do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));
// catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
これは、ハンドラ内で同期コードを呼び出す場合にのみ機能します。それ以外の場合は、ハンドラが無期限に呼び出されます。