我一直在尝试将程序中的某些工作分离到不同的线程中。 其中一个函数需要将流返回到主线程,但我遇到了以下异常:
Error
at MessagePort.<anonymous> ([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.<anonymous> (test/modules/templates/render.test.js:185:68)
我尝试构建一个最小化的示例来重现我想要实现的内容。基本上,我需要将一个可读流发送回主线程。在这个示例中,我还遇到了一个异常:
为了拥有一个工作线程池,我正在使用库node-worker-threads-pool,具体来说是DynamicPool。而在其中,我正在尝试将
html
转换为PDF。但我需要以某种方式将流返回给主线程。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) => {
const options = {
format: 'Letter',
};
return pdf.create(html, Object.assign(options, renderOptions || {}));
};
return Promise.fromNode((cb) => htmlToPdf(html, {}).toStream(cb));
},
workerData: {
html,
},
});
}
convertToPDF('<div>Hello World!</div>')
.then((resp) => console.log('resp', resp))
.catch((err) => console.error('err', err));
err DataCloneError: function() {
if (this.autoClose) {
this.destroy();
}
} could not be cloned.
at MessagePort.<anonymous> ([worker eval]:12:16)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
你有想法如何实现这个吗?
PS: 我知道在工作线程中IO操作不如在nodejs主线程中高效,但我需要这样做来避免用这些操作锁定主线程。