workerhelp
Version:
基于Node.js worker_threads 的轻量级跨线程RPC通信模块,支持主线程与Worker线程之间的异步方法调用。
55 lines (46 loc) • 1.42 kB
JavaScript
// worker_rpc.js
const { Worker, parentPort } = require('worker_threads');
const { randomUUID } = require('crypto');
class WorkerRPC {
constructor(workerPath) {
this.worker = new Worker(workerPath);
this.pending = new Map();
this.worker.on('message', (data) => this._handleResponse(data));
this.worker.on('error', (err) => this._handleError(err));
this.worker.on('exit', (code) => this._handleExit(code));
}
call(method, ...args) {
return new Promise((resolve, reject) => {
const id = randomUUID();
this.pending.set(id, { resolve, reject });
this.worker.postMessage({
type: 'request',
id,
method,
args
});
});
}
destroy() {
this.worker.terminate();
this.pending.forEach(({ reject }) =>
reject(new Error('Worker terminated')));
this.pending.clear();
}
_handleResponse({ id, error, result }) {
if (!this.pending.has(id)) return;
const { resolve, reject } = this.pending.get(id);
this.pending.delete(id);
error ? reject(new Error(error)) : resolve(result);
}
_handleError(err) {
for (const [id, { reject }] of this.pending) {
reject(err);
this.pending.delete(id);
}
}
_handleExit(code) {
this._handleError(new Error(`Worker exited with code ${code}`));
}
}
module.exports = { WorkerRPC };