UNPKG

@nodesecure/tarball

Version:
34 lines 1.05 kB
// Import Node.js Dependencies import { Worker } from "node:worker_threads"; export class PooledWorker { #worker; #currentTaskId = null; #events; constructor(workerPath, events) { this.#events = events; this.#worker = new Worker(workerPath); this.#worker.on("message", (message) => { this.#currentTaskId = null; this.#events.onComplete(this, message); }); this.#worker.on("error", (error) => { const taskId = this.#currentTaskId; this.#currentTaskId = null; this.#events.onError(this, error, taskId); }); } get isAvailable() { return this.#currentTaskId === null; } execute(task) { if (!this.isAvailable) { throw new Error(`Worker is busy with task ${this.#currentTaskId}`); } this.#currentTaskId = task.id; this.#worker.postMessage(task); } terminate() { return this.#worker.terminate(); } } //# sourceMappingURL=PooledWorker.class.js.map