My nodejs server dir structure is as following:
./src/rest/api/longJob.js
This file contains following method for long running operation, which I want to handover to worker:
const { Worker } = require('node:worker_threads')
async runWorker(scriptfile, input) {
console.log('Running worker python script:', scriptfile);
return new Promise(function(resolve, reject) {
const worker = new Worker("./src/rest/api/worker.js", {
workerData: {
thread_count: 3
},
});
worker.on("message", (data) => {
console.log("[[Worker]]:", data);
resolve(data);
});
worker.on("error", (msg) => {
reject(`An error ocurred: ${msg}`);
});
});
return p;
}
I am using promise, so that when the promise is resolved, I can send back the data as response to the rest-api.
The worker file is located at: ./src/rest/api/worker.js
import { parentPort, workerData } from "worker_threads";
async function worker() {
console.log("started");
parentPort.postMessage("fixed!");
}
console.log('worker executing');
worker();
whenever a new worker is created, the worker code is not executed and worker stays online.
The console logs from worker.js is also not printed in the js debug terminal for vscode. Not sure what is wrong with the code.
I start my nodejs application from . dir using npm start
. It would be helpful to get help on this.
Thanks!