I am implementing a program that can save the "session" of a running process by outputting a JSON object to a file. I want this saving to happen when the user hits Control+C.
I have implemented it as follows:
process.on('SIGINT', function() {
console.log('\nCaught Control+C. Saving session...');
filename = 'session_'+randomString(10)+'.saved';
fs.writeFileSync(filename, JSON.stringify({
'jobs': jobs,
'config': config,
'verbose': verbose,
'max_retries': max_retries
}), function(err) {
if (err) {
console.log('ERROR while saving session file!');
console.log(err);
return;
}
console.log('The session file was successfully saved to "'
+ filename + '"!');
process.exit();
});
});
I expect the last console.log
line to output The session file was successfully saved to session_blabla123.saved!
but the message is not printed. The file is saved correctly, this is not the problem. I just want to message to appear on the terminal.
I'm OK with having the program wait for a few seconds before quitting if that will fix the problem. I also tried:
console.log('The session file was successfully saved to "'+ filename + '"!');
setTimeout(function() {
process.exit();
}, 2000);
But the program still quits immediately. I've also looked into flushing the console output but there doesn't seem to be any good way to do that (looked at Is it possible to flush the console (make it print immediately)?)... is there any workable solution?