title: nodejs - Sending back a stream from a worker thread to the main thread
body: <p>I had been trying to separate some work that's done in my program in a different thread.
  One of the functions needs to return a stream to the main thread but I'm having the following exception:</p>
  
  <pre><code>Error
      at MessagePort.&lt;anonymous&gt; ([worker eval]:12:16)
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
  From previous event:
      at PoolWorker.work (node_modules/node-worker-threads-pool/src/pool-worker.js:22:12)
      at DynamicPool.runTask (node_modules/node-worker-threads-pool/src/pool.js:110:47)
      at DynamicPool.exec (node_modules/node-worker-threads-pool/src/dynamic-pool.js:51:17)
      at renderToPdf (src/modules/templates/render2.js:27:14)
      at Context.&lt;anonymous&gt; (test/modules/templates/render.test.js:185:68)
  </code></pre>
  
  <p>I tried to construct a minimal example to reproduce what I'm trying to achieve. Basically, what I need is to send back a readable stream to the main thread. In this example, I'm also having a exception:</p>
  
  <p>To have a pool of worker threads I'm using the library <a href="https://github.com/SUCHMOKUO/node-worker-threads-pool#readme" rel="noreferrer">node-worker-threads-pool</a> the DynamicPool specifically. And inside I'm trying to convert <code>html</code> to a PDF. But I need to somehow return the stream to the main thread.</p>
  
  <pre class="lang-js prettyprint-override"><code>const os = require('os');
  const { DynamicPool } = require('node-worker-threads-pool');
  
  const Pool = new DynamicPool(os.cpus().length);
  
  async function convertToPDF(html) {
    return await Pool.exec({
      task: function() {
        const Promise = require('bluebird');
        const pdf = require('html-pdf');
  
        const { html } = this.workerData;
  
        const htmlToPdf = (html, renderOptions) =&gt; {
          const options = {
            format: 'Letter',
          };
          return pdf.create(html, Object.assign(options, renderOptions || {}));
        };
  
        return Promise.fromNode((cb) =&gt; htmlToPdf(html, {}).toStream(cb));
      },
      workerData: {
        html,
      },
    });
  }
  
  convertToPDF('&lt;div&gt;Hello World!&lt;/div&gt;')
    .then((resp) =&gt; console.log('resp', resp))
    .catch((err) =&gt; console.error('err', err));
  </code></pre>
  
  <pre><code>err DataCloneError: function() {
      if (this.autoClose) {
        this.destroy();
      }
    } could not be cloned.
      at MessagePort.&lt;anonymous&gt; ([worker eval]:12:16)
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
  </code></pre>
  
  <p>Do you have an idea of how can I achieve this?</p>
  
  <p>PS: I'm aware that the IO operations are not as performant in the worker threads are they are in the nodejs main thread, but I need to do this to avoid locking the main thread with these operations.</p>