我想告诉Node.js无论出于何种原因(Ctrl+ C,异常或任何其他原因)总是在退出之前总是做一些事情。
Ctrl
C
我尝试了这个:
process.on('exit', function (){ console.log('Goodbye!'); });
我开始了该过程,将其杀死,但没有任何反应。我再次启动它,按Ctrl+ C,仍然没有任何反应…
您可以注册一个处理程序,process.on('exit')并在任何其他情况下(SIGINT或未处理的异常)进行调用process.exit()
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}));