Offload tasks to a pool of workers on node.js and in the browser
npx @tessl/cli install tessl/npm-workerpool@9.3.0workerpool offers an easy way to create a pool of workers for both dynamically offloading computations as well as managing a pool of dedicated workers. It implements a thread pool pattern with a natural, promise-based proxy interface, making workers accessible as if they are available directly in the main application.
workerpool runs on Node.js and in the browser, automatically selecting the appropriate worker type (Web Workers, child processes, or worker threads) based on the environment.
npm install workerpoolconst workerpool = require('workerpool');For ES modules:
import workerpool from 'workerpool';
// or
import { pool, worker, workerEmit } from 'workerpool';const workerpool = require('workerpool');
// Create a worker pool
const pool = workerpool.pool();
// Offload a function dynamically
function fibonacci(n) {
if (n < 2) return n;
return fibonacci(n - 2) + fibonacci(n - 1);
}
pool
.exec(fibonacci, [10])
.then(function (result) {
console.log('Result:', result); // 55
})
.catch(function (err) {
console.error(err);
})
.then(function () {
pool.terminate(); // terminate all workers when done
});ES modules example:
import workerpool from 'workerpool';
// Create a worker pool
const pool = workerpool.pool();
// Offload a function dynamically with async/await
const fibonacci = (n) => {
if (n < 2) return n;
return fibonacci(n - 2) + fibonacci(n - 1);
};
try {
const result = await pool.exec(fibonacci, [10]);
console.log('Result:', result); // 55
} catch (err) {
console.error(err);
} finally {
await pool.terminate(); // terminate all workers when done
}workerpool is built around several key components:
Pool class manages a pool of workers, handling task queuing, worker allocation, and lifecycle managementworker module provides utilities for registering functions and handling communication within worker processesCore functionality for creating and managing pools of workers. Handles dynamic function offloading, dedicated worker scripts, and worker lifecycle management.
function pool(script, options) -> Pool
function pool(options) -> Pool
interface Pool {
exec(method, params, options) -> Promise
proxy() -> Promise<ProxyObject>
terminate(force, timeout) -> Promise<void>
stats() -> PoolStats
}Utilities for setting up worker processes, registering functions, and handling communication between main thread and workers.
function worker(methods, options) -> void
function workerEmit(payload) -> void
// Available within worker context
interface WorkerAPI {
addAbortListener(listener) -> void
emit(payload) -> void
}Enhanced Promise implementation with cancellation and timeout support, plus utilities for transferring objects between workers.
class Promise {
constructor(handler, parent)
then(onSuccess, onFail) -> Promise
catch(onFail) -> Promise
cancel() -> Promise
timeout(delay) -> Promise
always(fn) -> Promise
finally(fn) -> Promise
}
class Transfer {
constructor(message, transfer)
}Promise and Transfer Utilities
const platform: 'node' | 'browser'
const isMainThread: boolean
const cpus: numberThese constants provide information about the current execution environment and are useful for conditional logic based on platform capabilities.
interface WorkerPoolOptions {
minWorkers?: number | 'max'
maxWorkers?: number
maxQueueSize?: number
workerType?: 'auto' | 'web' | 'process' | 'thread'
workerTerminateTimeout?: number
forkArgs?: string[]
forkOpts?: object
workerOpts?: object
workerThreadOpts?: object
emitStdStreams?: boolean
onCreateWorker?: (args: WorkerArg) => WorkerArg | undefined
onTerminateWorker?: (args: WorkerArg) => void
}
interface ExecOptions {
on?: (payload: any) => unknown
transfer?: object[]
}
interface WorkerRegisterOptions {
onTerminate?: (code: number | undefined) => PromiseLike<void> | void
abortListenerTimeout?: number
}
interface PoolStats {
totalWorkers: number
busyWorkers: number
idleWorkers: number
pendingTasks: number
activeTasks: number
}
interface WorkerArg {
forkArgs?: string[]
forkOpts?: object
workerOpts?: object
workerThreadOpts?: object
script?: string
}