title: How to listen terminate signal from worker in nodejs?
body: <p>I have a main process which spawn one new thread using <code>worker_threads</code>. Main process in some particular cases have to close this thread without mattering if it has finished its task or not, so MainThread makes use of <a href="https://nodejs.org/api/worker_threads.html#worker_threads_worker_terminate" rel="nofollow noreferrer">terminate()</a> to stop the thread. However, this thread spawn different dependencies that need to be closed before exiting. These dependencies have to be closed from the thread, so I cannot use <code>worker.on('exit')</code> since it is run on main process.</p>
  <p>Is there some way of listening the terminate from the worker itself?</p>
  <p>Some minimal example of what I would like to achieve.</p>
  <pre><code>const {Worker, isMainThread} = require('worker_threads');
  
  if (isMainThread) {
    const worker = new Worker(__filename);
    worker.on('message', console.log);
    worker.on('error', console.log);
    worker.on('exit', console.log);
  
    setTimeout(() =&gt; {
      console.log('Worker is gonna be terminated');
      worker.terminate();
    }, 5000);
  } else {
    (async () =&gt; {
      console.log('I am the worker');
      // This thread will spawn its own dependencies, so I want to listen here the terminate signal from 
      // mainThread to close the dependencies of this worker
      // Sth like the following will be awesome
      // thread.on('exit', () =&gt; { /* close dependencies */ })
  
      // Simulate a task which takes a larger time than MainThread wants to wait
      await new Promise(resolve =&gt; {
        setTimeout(resolve, 10000);
      });
    })();
  }
  </code></pre>