0

That is my code, I tried two ways to trigger a callback function when process exit.

My purpose is when process exit, it can write some word to a txt file.

The way I exit process is click the 'close' button on the node.exe window,the other way is key Ctrl+C.

But both of these methods are not effective.

process.on('exit', function() {
  chatCache.each(function(i,self,length){
    util.writeJSONtoTxt(chatChache_filePath,JSON.stringify(self));
});
});
//--------------------------------------------
var stdin = process.openStdin();

process.on('SIGINT', function () {
 console.log('Got SIGINT.  Press Control-D to exit.');
 chatCache.each(function(i,self,length){
    util.writeJSONtoTxt(chatChache_filePath,JSON.stringify(self));
});
});
4

1 回答 1

1

您必须像这样从SIGINT处理程序中终止进程:

process.on('SIGINT', function() {
 console.log('Got SIGINT.  Going to exit.');
 //Your code to execute before process kill.
 process.kill(process.pid);
});

然后它会在你按Ctrl+时退出C

process.on('exit', function() {});仅当您的 node.js 代码完成执行(完成事件循环)且没有任何错误时才会执行,如果您运行服务器,这将永远不会发生。

于 2013-05-11T03:27:26.933 回答