jellobird
jellobird

Reputation: 797

Is it possible to wait for a child_process in process.on('exit', ...) method

I'm trying the following

process.on('exit', function() {
    child_process.exec('echo hello', /*...*/);
}

and want to delay exit until the child process has finished.

Is this possible?

Upvotes: 0

Views: 2326

Answers (1)

hassansin
hassansin

Reputation: 17498

Nope, according to doc, exit event is too late to bind any async events. You should instead listen for beforeExit event.

Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler.

In beforeExit you can do async operation and exit manually:

process.on('beforeExit', function() {
  setTimeout(function(){ //run async code
    console.log('beforeExit')
    process.exit(0);  //exit manually
  }, 1000);
});

Upvotes: 2

Related Questions