How to Prevent a Node.js 12 worker Thread from terminating immediately?
I'm mostly spitballin' here, but I think this'll put you on the right track:
add to start.js
process.on('SIGTERM', cleanup);process.on('SIGINT', cleanup);myWorker.once('exit', stop);function cleanup() { myWorker.postMessage('cleanup');}
worker.js
const { parentPort } = require('worker_threads');parentPort.on('message', (value) => { if (value === 'cleanup') { cleanup(); //then process.exit(0); }});
The following solution should work-
- Subscribe to main thread
message
event in the worker thread - Subscribe to
SIGTERM
(or whatever) in the main thread - When you catch the signal in the main thread, send a message to the worker thread, requesting it to clean up and exit. ** Do not exit from the main thread yet**.
- In the main thread wait for worker thread to stop by subscribing to
exit
event. - When worker thread stops, exit from the main thread.