coreybutler / node-windows

Windows support for Node.JS scripts (daemons, eventlog, UAC, etc).
Other
2.83k stars 356 forks source link

Handling child_process events #213

Closed AshishShanker closed 6 years ago

AshishShanker commented 6 years ago

I need a mechanism to handle child_process events.

In the current architecture, the child_process that runs my script is spawned by wrapper.js which has a handler for child.on('exit',...), but affords no opportunity for the application programmer to add additional listeners for exit or other events.

The use case I want to enable is a general clean up that the script would do (e.g. close down db connections, sign-off from streams, etc.) when the Windows Service is Stopped by the user from the Services control.

I tried putting in process.on(['exit'|'SIGINT'|'SIGTERM'|...], handler_func) in my script, but none of these events trigger because the global process object applies to the spawning node process, not the child_process.

Perhaps, it may make sense to expose a handlers object in the Service object, so user-defined child_process handlers could be passed onto wrapper.js to wire up with the child_process at the time it does a fork()?

I know I am asking for an API change, and that needs to be weighed with impact on node-linux and node-mac as well, but it would be great to know how others have solved the problem of handling user initiated Windows service shutdown.

AshishShanker commented 6 years ago

The solution to this problem is not to listen to any of the events mentioned, instead look for a message 'shutdown'. So this works:

process.on('message' async (msg) => { // do whatever cleanup necessary, with await to allow adequate time for the clean up to happen }