worker-spawner
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

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 to true, the worker thread will be unref'd. Defaults to false.
    • timeout: The timeout in milliseconds after which the worker will be terminated. Defaults to 0 (no timeout).
  • workerOptions(optional): Additional worker options respecting the WorkerOptions Interface

Tests

You can run the tests by using the following command:

npm test

Package Sidebar

Install

npm i worker-spawner

Weekly Downloads

3

Version

2.0.2

License

MIT

Unpacked Size

7.01 kB

Total Files

8

Last publish

Collaborators

  • cadienvan