我想告诉Node.js总是在它退出之前做一些事情,无论出于什么原因- Ctrl+C,一个异常,或任何其他原因。
我试了一下:
process.on('exit', function (){
console.log('Goodbye!');
});
我启动了这个程序,扼杀了它,然后什么都没发生。我再次启动,按下Ctrl+C,仍然什么都没有发生……
我想告诉Node.js总是在它退出之前做一些事情,无论出于什么原因- Ctrl+C,一个异常,或任何其他原因。
我试了一下:
process.on('exit', function (){
console.log('Goodbye!');
});
我启动了这个程序,扼杀了它,然后什么都没发生。我再次启动,按下Ctrl+C,仍然什么都没有发生……
当前回答
这里有一个针对windows的好方法
process.on('exit', async () => {
require('fs').writeFileSync('./tmp.js', 'crash', 'utf-8')
});
其他回答
function fnAsyncTest(callback) {
require('fs').writeFile('async.txt', 'bye!', callback);
}
function fnSyncTest() {
for (var i = 0; i < 10; i++) {}
}
function killProcess() {
if (process.exitTimeoutId) {
return;
}
process.exitTimeoutId = setTimeout(() => process.exit, 5000);
console.log('process will exit in 5 seconds');
fnAsyncTest(function() {
console.log('async op. done', arguments);
});
if (!fnSyncTest()) {
console.log('sync op. done');
}
}
// https://nodejs.org/api/process.html#process_signal_events
process.on('SIGTERM', killProcess);
process.on('SIGINT', killProcess);
process.on('uncaughtException', function(e) {
console.log('[uncaughtException] app will be terminated: ', e.stack);
killProcess();
/**
* @https://nodejs.org/api/process.html#process_event_uncaughtexception
*
* 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process.
* It is not safe to resume normal operation after 'uncaughtException'.
* If you do use it, restart your application after every unhandled exception!
*
* You have been warned.
*/
});
console.log('App is running...');
console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);
process.stdin.resume();
// just for testing
在进程由另一个节点进程生成的情况下,例如:
var child = spawn('gulp', ['watch'], {
stdio: 'inherit',
});
然后你试图通过以下方式杀死它:
child.kill();
这是如何处理[子]事件的:
process.on('SIGTERM', function() {
console.log('Goodbye!');
});
Async-exit-hook似乎是处理这个问题的最新解决方案。它是退出钩子的分叉/重写版本,在退出前支持异步代码。
这里有一个针对windows的好方法
process.on('exit', async () => {
require('fs').writeFileSync('./tmp.js', 'crash', 'utf-8')
});
我需要在退出时做一个异步清理操作,这个问题的答案都不适合我。
所以我自己试了一下,最后发现了这个:
process.once('uncaughtException', async () => {
await cleanup()
process.exit(0)
})
process.once('SIGINT', () => { throw new Error() })