worker-spawner
v2.0.2
Published
A Worker Thread spawner for Node.js with a simple API.
Downloads
80
Maintainers
Readme
What is this?
A Worker Thread spawner for Node.js with a simple API.
How do I install it?
npm install worker-spawner
How can I use it?
You can find a simple example in the examples
folder.
Basic usage
My script:
const { workerThreadExecute } = require('worker-spawner');
const myExpensiveFunction = await workerThreadExecute(__dirname + '/blocking-expensive-function.js', myInput);
console.log(myExpensiveFunction);
My worker:
const { parentPort } = require('worker_threads');
parentPort.on('message', (input) => {
// Do some expensive stuff
myOutput = input.map((item) => item * 2);
parentPort.postMessage(myOutput);
});
Advanced usage - Preloading
My script:
const { Worker } = require('worker_threads');
const { workerThreadExecute } = require('worker-spawner');
const preloadedWorker = new Worker(__dirname + '/blocking-expensive-function.js');
const myExpensiveFunction = await workerThreadExecute(preloadedWorker, myInput);
console.log(myExpensiveFunction);
My worker:
const { parentPort } = require('worker_threads');
parentPort.on('message', (input) => {
// Do some expensive stuff
myOutput = input.map((item) => item * 2);
parentPort.postMessage(myOutput);
});
API
The workerThreadExecute function takes two arguments:
workerPathOrInstance
(required): Either a path to a worker file or a preloaded worker instance.payload
(optional): The input to be passed to the worker. This input will be passed to the worker as a message.options
(optional): An object containing the following properties:unref
: If set totrue
, the worker thread will be unref'd. Defaults tofalse
.timeout
: The timeout in milliseconds after which the worker will be terminated. Defaults to0
(no timeout).
workerOptions
(optional): Additional worker options respecting the WorkerOptions Interface
Tests
You can run the tests by using the following command:
npm test