In Nodejs, using Express as a server, I offload a heavy computation onto a worker thread.
From the main application, I call the worker thread like this:
// 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
);
});
The worker looks like this:
// 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);
}
The worker generates a huge amount of data and "postMessage" causes a server error.
Is there a way to send this data from the worker thread directly to the client, using res.send()
or something alike?
(instead of using postMessage
and then sending from the main thread)?