在 Nodejs 中,使用 Express 作为服务器,我将繁重的计算卸载到工作线程上。
在主应用程序中,我这样调用工作线程:
// file: main.js
const { Worker } = require("worker_threads");
function runService(fileName, workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker(fileName, { workerData });
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", code => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}
router.get("/some_url", async function(req, res) {
const result = await runService(
"./path/to/worker.js",
{ query: req.query, user: req.user } // using { req } causes an error
);
});
工人看起来像这样:
// file: worker.js
const { workerData, parentPort } = require('worker_threads');
const { query, user } = workerData;
async function run() {
const result = await generateLotsOfData(query, user);
parentPort.postMessage(result);
// What I would like to do here (doesn't work): res.send(result);
}
工作人员生成大量数据,“postMessage”导致服务器错误。
有没有办法将这些数据从工作线程直接发送到客户端,使用res.send()
或类似的东西?
(而不是使用postMessage
然后从主线程发送)?