我想告诉Node.js总是在它退出之前做一些事情,无论出于什么原因- Ctrl+C,一个异常,或任何其他原因。

我试了一下:

process.on('exit', function (){
    console.log('Goodbye!');
});

我启动了这个程序,扼杀了它,然后什么都没发生。我再次启动,按下Ctrl+C,仍然什么都没有发生……


当前回答

"exit"是一个在节点内部完成它的事件循环时触发的事件,当你在外部终止进程时不会触发。

你要做的是在SIGINT上执行一些东西。

http://nodejs.org/api/process.html#process_signal_events上的文档给出了一个例子:

监听SIGINT的例子:

// Start reading from stdin so we don't exit.
process.stdin.resume();

process.on('SIGINT', function () {
  console.log('Got SIGINT.  Press Control-D to exit.');
});

注意:这似乎会中断sigint,当你完成代码时,你需要调用process.exit()。

其他回答

这将捕获我能找到的可以处理的每个退出事件。目前看来很可靠,也很干净。

[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
  process.on(eventType, cleanUpServer.bind(null, eventType));
})

io.js有一个exit和一个beforeExit事件,它们做你想做的事情。

更新:

You can register a handler for `process.on('exit')` and in any other case(`SIGINT` or unhandled exception) to call `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}));

只有在处理程序内部调用同步代码时,这才有效,否则它将无限期地调用处理程序

在进程由另一个节点进程生成的情况下,例如:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',
});

然后你试图通过以下方式杀死它:

child.kill();

这是如何处理[子]事件的:

process.on('SIGTERM', function() {
    console.log('Goodbye!');
});

"exit"是一个在节点内部完成它的事件循环时触发的事件,当你在外部终止进程时不会触发。

你要做的是在SIGINT上执行一些东西。

http://nodejs.org/api/process.html#process_signal_events上的文档给出了一个例子:

监听SIGINT的例子:

// Start reading from stdin so we don't exit.
process.stdin.resume();

process.on('SIGINT', function () {
  console.log('Got SIGINT.  Press Control-D to exit.');
});

注意:这似乎会中断sigint,当你完成代码时,你需要调用process.exit()。