user1084563
user1084563

Reputation: 2169

Node.js intercepting process.exit

So I wanted to run a shell command at the end of my node.js program and wait for the output/print it before exiting. I tried process.on('exit',function(){}) and running the child exec command in there but the program exited before the callback. So instead I used a closure on process.exit but I am getting some strange results. The basics of the code is:

 process.exit = (function(old_exit){
   return function(code){
     var exec = require('child_process').exec;
     var child;
     child = exec("my shell command", function (error, stdout, stderr) {
       if (error !== null) {
         console.log('exec error: ' + error);
       }
       console.log(stdout);
       //I first had this as the concluding line:
       old_exit.apply(process,arguments);
       //and I also tried
       old_exit.apply(process,[]);
       //and even (which I know is not in the right scope)
       old_exit(code);
       //and also
       process.exit = old_exit;
       process.exit(code);
     });
   }
 }(process.exit));

Every one of the above results executed my shell command exactly twice and then exited. I also tried not calling anything at the end and while that kept it so that my command executed only once, the process hung instead of exiting at the end. Unless there is something simply I'm missing I feel like the first attempt I had old_exit.apply(process,arguments); would be the correct way and should not be calling my own code again, it does. I also tried used promises which didn't work (it didn't even throw an error for being resolved multiple times) and I tried using a boolean for if it had been set but that didn't work either. I finally even tried throwing an error after the callback finished but this forced process.exit to be called again after the error. Any ideas?

Upvotes: 10

Views: 7454

Answers (1)

Jonathan Wiepert
Jonathan Wiepert

Reputation: 1242

By process.exit time, you are too late to do anything async. I do not think you can get around the async part, as you apparently need to execute a shell command. You can listen for various exit signals, do your async stuff, then call process.exit yourself when you are ready. Note you will get a all signals until the process exists, so you will want to track the state to ensure your shell command is only run once. The following will work for the ctrl-c signal:

process.on('SIGINT', function() {
    console.log('Received Signal');
    setTimeout(function() {
        console.log('Exit');
        process.exit(1);
    }, 10000);
});

Upvotes: 10

Related Questions