UNPKG

node-worker-threads-pool-ts

Version:

Simple worker threads pool using Node's worker_threads module. Compatible with ES6+ Promise, Typescript, Async/Await.

86 lines (83 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StaticPool = void 0; const pool_1 = require("./pool"); const pool_worker_1 = require("./pool-worker"); const task_executor_1 = require("./task-executor"); const create_code_1 = require("./create-code"); const worker_threads_1 = require("worker_threads"); function createScript(fn) { return ` const { parentPort, workerData } = require('worker_threads'); this.workerData = workerData; const container = { workerData, require, task: ${create_code_1.createCode(fn)} }; process.once("unhandledRejection", (err) => { throw err; }); parentPort.on('message', async (param) => { parentPort.postMessage(await container.task(param)); }); `; } /** * Threads pool with static task. */ class StaticPool extends pool_1.Pool { constructor(opt) { super(opt.size); const { workerData, shareEnv, resourceLimits, isDone } = opt; let task = opt.task; const workerOpt = { workerData }; /* istanbul ignore next */ if (shareEnv) { workerOpt.env = worker_threads_1.SHARE_ENV; } /* istanbul ignore next */ if (typeof resourceLimits === "object") { workerOpt.resourceLimits = resourceLimits; } if (typeof task === "function") { workerOpt.eval = true; } switch (typeof task) { case "string": { if (task.endsWith(".ts")) { workerOpt.argv = [task]; task = __dirname + "/register.js"; } this.fill(() => new pool_worker_1.PoolWorker(task, workerOpt, isDone)); break; } case "function": { const script = createScript(task); this.fill(() => new pool_worker_1.PoolWorker(script, workerOpt, isDone)); break; } default: throw new TypeError("Invalid type of 'task'!"); } } /** * Choose a idle worker to run the task * with param provided. */ exec(param, timeout = 0) { if (typeof param === "function") { throw new TypeError('"param" can not be a function!'); } return this.runTask(param, { timeout }); } /** * Create a task executor of this pool. * This is used to apply some advanced settings to a task. */ createExecutor() { return new task_executor_1.StaticTaskExecutor(this); } } exports.StaticPool = StaticPool; //# sourceMappingURL=static-pool.js.map