2013-05-10 139 views
0

這是我的代碼,我嘗試了兩種方式來在進程退出時觸發回調函數。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)); 
}); 
}); 
+0

..我的英語很差... – moe 2013-05-10 10:52:39

+0

@Rakkun,如何使用同步通話?謝謝! – moe 2013-05-10 11:30:39

回答

0

你必須殺死從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代碼完成執行(結束事件循環)時沒有任何錯誤纔會執行,如果您運行服務器,這絕不會發生。

相關問題