To contextualize, I would like to use class instances functions through a Worker Thread from NodeJS "worker_thread" module.
In one main.js
file I declare a class and instanciate a new Worker passing the new instance through the workerData
option.
main.js
const { Worker } = require('worker_threads');
class obj {
constructor() {
this.a = "12";
this.b = 42;
}
c() {
return 'hello world';
}
}
let newobj = new obj();
console.log({
a: newobj.a,
b: newobj.b,
c: newobj.c()
});
//Output: { a: '12', b: 42, c: 'hello world' }
let worker = new Worker('./process.js', { workerData: { obj: newobj } });
worker.once('message', res => { console.log({ res }) });
As you may see, the worker called the process.js
script.
Let see it.
process.js
const { parentPort, workerData } = require('worker_threads');
let { obj } = workerData;
console.log({
a: obj.a,
b: obj.b,
c: obj.c()
});
parentPort.postMessage('DONE');
As you know, this code throw an error: TypeError: obj.c is not a function
. In fact, after checking Worker Thread documentation (https://nodejs.org/dist./v10.22.0/docs/api/worker_threads.html#worker_threads_new_worker_filename_options) I discover that Worker could not be an Object with function. In reality, it works but all functions are not cloned.
I am really confused because I do not know how to solve this problem. In fact, this exemple is easy because of simplify a complex situation but in my case I absolutly need to call the c function in process.js
side but I do not know how to do it differently.
I hope you may help me. Thanks in advance for your time.