1

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));
});
});
2
  • ..My english is so poor... Commented May 10, 2013 at 10:52
  • @Rakkun ,how to use synchronous call ? Thx! Commented May 10, 2013 at 11:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.