3

I am attempting to create a way to gracefully shutdown my server, but it does not seem that the method being called in response to a SIGINT is completely finishing.

I have added a callback function to the SIGINT signal using process.on('SIGINT', cb)

var stop = () => {
  console.log("stopping server");
  return new Promise((resolve, reject) =>
    server.close(() => { console.log("server closed"); resolve(); }))
    .then(() => new Promise((resolve, reject) => setTimeout(() => { console.log("time out finished"); resolve(); }, 5000)))
    .then(() => process.exit(0));
}

process.on("SIGINT", stop);

I added the setTimeout in there just as a test to see if the server is waiting before completely shutting down.

When I send SIGINT to the process, the output I get is

stopping server

On a few occasions both the stopping server and the server closed logs come through, but not all the time.

I have tried implementing the wait function from this previous question: How to prevent Node.js from exiting while waiting for a callback?, but I still achieve the same results as above.

Does anyone know a workaround that will allow this method to completely finish before the server exits?

1 Answer 1

0

I was having real trouble with this and using neither promises nor callbacks seemed to work. For myself, I think the process queue emptied (and node exited) before my winston logger would save all info to files.

In any case, I eventually got around to solving it by putting in manual flags for each process I wanted to exit to return true once done. The exit itself was in an 100ms interval and would only exit on all flags true.

e.g.

process.on('SIGINT', exit);

function exit(){
    var myProcessFlag = myProcess.close()    //returns true once complete

    setInterval(function(){
        if(myProcessFlag == true){
            console.log('successful exit');
            process.exit(0);
        }
        else{
            console.log(`awaiting...
                         myProcess complete: ${myProcessFlag}`);
        }
    }, 100);
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.