没实践过,不知道有没有别的坑,思路就是把函数转为字符串,worker 中再把字符串转回来
```js
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
if (isMainThread) {
const obj = {
name: 'Foo',
greet(other) {
return `Hello ${
this.name} and ${other}`;
}
}
const objStr = JSON.stringify(obj, (key, value) => {
if (typeof value === 'function') {
return value.toString();
}
return value;
});
const worker = new Worker(__filename, {
workerData: objStr,
});
worker.on('message', (value) => {
console.log('Receive data from worker =>', value);
});
worker.on('error', console.error);
worker.on('exit', (code) => {
if (code !== 0)
console.error(new Error(`Worker stopped with exit code ${code}`));
});
} else {
const objStr = workerData;
const objParsed = JSON.parse(objStr);
const run = (obj, funcName, ...args) => {
if (obj.hasOwnProperty(funcName)) {
const funcStr = obj[funcName];
// 提取函数体,忽略函数参数定义
const funcBody = funcStr.substring(obj.greet.indexOf('{') + 1, obj.greet.lastIndexOf('}'));
// 使用剩余参数语法来定义一个新的函数,允许接收任意数量的参数
const funcArgs = funcStr.substring(funcStr.indexOf('(') + 1, funcStr.indexOf(')')).split(',').map(arg => arg.trim()).filter(arg => arg);
const func = new Function(...funcArgs, funcBody);
return func.call(obj, ...args);
}
}
const result = run(objParsed, 'greet', 'Bar');
parentPort.postMessage(result);
}
```