node.js进程在退出时如何触发回调函数?
问题描述:
这是我的代码,我尝试了两种方式来在进程退出时触发回调函数。node.js进程在退出时如何触发回调函数?
我的目的是当进程退出时,它可以写一些字到一个txt文件。
我退出过程的方法是点击node.exe
窗口上的“关闭”按钮,另一种方法是关键按Ctrl +Ç。
但这两种方法都无效。
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));
});
});
答
你必须杀死从SIGINT
处理这样的过程:
process.on('SIGINT', function() {
console.log('Got SIGINT. Going to exit.');
//Your code to execute before process kill.
process.kill(process.pid);
});
然后,它会退出,当你按下Ctrl键+Ç。
process.on('exit', function() {});
仅当您的node.js代码完成执行(结束事件循环)时没有任何错误才会执行,如果您运行服务器,这绝不会发生。
..我的英语很差... – moe 2013-05-10 10:52:39
@Rakkun,如何使用同步通话?谢谢! – moe 2013-05-10 11:30:39