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));
});
});
You have to kill the process from SIGINT handler like this :
process.on('SIGINT', function() {
console.log('Got SIGINT. Going to exit.');
//Your code to execute before process kill.
process.kill(process.pid);
});
Then it will exit when you press Ctrl+C .
process.on('exit', function() {}); is only executed when your node.js code completes executing (finishes event loop) without any errors, which will never happen if you run a server.