node-windows icon indicating copy to clipboard operation
node-windows copied to clipboard

How to Handle Stopping a Service

Open pbaio opened this issue 9 years ago • 2 comments

I'm using node-windows and it works great for everything other than stopping and the answer provided in #75 is not what I'm looking for.

If I stop my service using say the Service UI and click "Stop" on my running service, it will shutdown the process but none of my graceful termination code is called. I've tried using the death to listen for SIGINT, SIGUP, SIGTERM but no avail (similar to #114). I've also tried listening for the 'stop' event on my service but that doesn't get fired either, my guess is that it only fires when svc.stop() is called from within the app itself.

How can my app know when the service is stopped from outside the current code? What should I be listening for?

pbaio avatar Sep 14 '16 17:09 pbaio

There's currently no clean way to listen for the stop event from within the application itself. Most daemon managers frown on this approach because it is possible for a process to run wild by preventing it from ever closing. I'm not necessarily opposed to this functionality, but I view it as a new feature and I'm pretty swamped.

If one wanted to do this now, I'd start by looking into the wrapper. The trick would be replacing the exec method with a spawn. You could then listen for the stop event and use the message passing capabilities of a spawned child to forward to your app. The app would need to handle these messages.

If anyone attempted this and submitted a PR, it would also need to be applied to node-mac and node-linux to maintain uniformity across the projects.

coreybutler avatar Sep 14 '16 22:09 coreybutler

I want to point out that when service is installed with option stopparentfirst: true the wrapper.js will send a shutdown message to the node script, which you can listen to and perform a graceful shutdown.

E.g.

    svc = new Service({
        name: 'My Service',
        script: path.join(projectRoot, 'daemon.js')
        stopparentfirst: true
    });

And then in daemon.js:

process.on('message', m => {
    if (m == 'shutdown') {
        winston.log('warn', `Service is stopping`, function(err, level, msg, meta) {
            // put your cleanup logic here
            // finally exit
            process.exit();
        });
    }
});

muxa avatar Jul 04 '17 09:07 muxa