title: Can one prevent a node.js worker from exiting the main process
body: <p>I am using nodejs 12 and this questions is related to <a href="https://nodejs.org/api/worker_threads.html" rel="nofollow noreferrer">https://nodejs.org/api/worker_threads.html</a>
  I know that Workers are sharing the same process as the main JS "thread"; still I am wondering if there's a way to prevent any error in the worker code from crashing the main process.</p>
  
  <p>I want to use a worker thread instead of forked process but this issue would be a blocker.</p>
  
  <p><code>worker.js</code></p>
  
  <pre class="lang-js prettyprint-override"><code>const { parentPort } = require( "worker_threads");
  
  let i = 0;
  setInterval(() =&gt; {
    parentPort.postMessage({ hello: "world" });
    i++;
    if (i &gt; 5) {
      throw new Error('Hello'); // imagine here some error that hasn't been caught
    }
  }, 200);
  
  setInterval(() =&gt; {
    parentPort.postMessage({ foo: "bar" });
  }, 600);
  </code></pre>
  
  <p><code>index.js</code></p>
  
  <pre class="lang-js prettyprint-override"><code>const { Worker } = require("worker_threads");
  const worker = new Worker("./worker.js");
  
  worker.on("error", (err) =&gt; {
    console.error(err);
  });
  
  worker.on("exit", () =&gt; {
    console.log('Worker exited')
  });
  
  worker.on("message", msg =&gt; {
    console.log(msg)
  });
  </code></pre>
  
  <p><code>Output</code></p>
  
  <pre class="lang-sh prettyprint-override"><code>➜ node index.js
  { hello: 'world' }
  { hello: 'world' }
  { foo: 'bar' }
  { hello: 'world' }
  { hello: 'world' }
  { hello: 'world' }
  { foo: 'bar' }
  { hello: 'world' }
  Error: Something happened
      at Timeout._onTimeout (/Users/micael/Desktop/crashing/worker.js:10:11)
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)
  Worker exited
  </code></pre>