2

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?

Daniel Gray
  • 1,697
  • 1
  • 21
  • 41
  • Are you using Node.js on Windows? As far as I know, `SIGINT` is not always correctly dispatched on Windows. – XCS Apr 19 '18 at 17:04
  • https://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js – XCS Apr 19 '18 at 17:05
  • No, I'm using it on Mac OS X. The SIGINT handler itself is working fine (the session file is being saved correctly). It's just that the console message isn't being printed... *sometimes* the initial "Saving session..." message is printed, but most of the time, nothing is. – Daniel Gray Apr 19 '18 at 17:21

0 Answers0