workerpool
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
Workerpool is a robust JavaScript tool that is used to optimize the process of offloading tasks to a pool of workers in both Node.js and browser environments. It essentially implements a thread pool pattern where a series of dedicated workers are maintained, executing tasks one at a time and picking new ones from a queue once finished. An important feature of workerpool is the ability to manage these workers via a promise-based proxy that handles tasks dynamically. It also handles crashed workers, supports setting a timeout, and runs in several environments, including Node.js and most modern browsers.
Workerpool is remarkably easy to use, and the package can be installed using npm with the command npm install workerpool
. Once installed, workerpool can be required in a Node.js application or loaded in a browser. To utilize it, you can either offload functions dynamically to a worker for execution, or create dedicated workers in a separate script.
For example, if you want to offload a function add
that adds two numbers, you can use the following script:
const workerpool = require('workerpool');
const pool = workerpool.pool();
function add(a, b) {
return a + b;
}
pool
.exec(add, [3, 4])
.then(function (result) {
console.log('result', result); // outputs 7
})
.catch(function (err) {
console.error(err);
})
.then(function () {
pool.terminate(); // terminate all workers when done
});
For dedicated workers, you can create them in a separate script and use them via a worker pool. A simple example:
const workerpool = require('workerpool');
// a deliberately inefficient implementation of the Fibonacci sequence
function fibonacci(n) {
if (n < 2) return n;
return fibonacci(n - 2) + fibonacci(n - 1);
}
// create a worker and register public functions
workerpool.worker({
fibonacci: fibonacci,
});
Workerpool's detailed documentation, which includes an extensive application interface (API) description, usage examples, a development roadmap and more, can be found within the package's GitHub repository. Besides the excellent readme file, other useful resources include the examples directory in the repository: https://github.com/josdejong/workerpool/tree/master/examples.