npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

worker-union

v2.2.0

Published

🤼‍♂️ Package that makes it easy and convenient to use native worker_threads module

Downloads

220

Readme

worker-union

Every Node.JS developer is aware of the single-threaded nature of this platform where everything except your Javascript code runs in parallel.. But what if I tell you that it has become possible to run JS in parallel as well?

The worker_threads module has been added to node.js v10.5.0, which allows javascript to be executed in separate threads within a single Node.JS process. Yes, no spawn, exec, fork, cluster and other parodies on multithreading!

Worker-union allows you to take advantage of worker_threads, while eliminating the need to manually manage messaging, the number of threads, load balancing between them, and so on.

Just write logic, the rest will be done by promise-powered worker-union 🤓

Let’s jump into it?

Requirements

Since module 'worker_threads' was added only in Node.JS v10.5.0, you cannot use 'worker-union' in earlier versions.

Also, when you start your application, you will need to use --experimental-worker flag (ex. node --experimental-worker index.js)

Install

npm i -S worker-union

Workerify

You can save yourself from the boilerplate at all, using the workerify! Just pass on your function and get an asynchronous wrapper. The code of the function itself will be executed in the Worker Pool.

const workerify = require('worker-union/workerify');

const parseJSON = value => JSON.parse(value);

const asyncParseJSON = workerify(parseJSON);

asyncParseJSON('{"foo":"bar"}').then(result => result.foo); // -> bar

It is important to know that your function must be serializable. You can easily verify this using func.toString() method. If you want to workerify the native Node.JS function, for example JSON.parse() (when you call func.toString() you see [native code]), then wrap it as in the example above.

By default, worker-union will allocate for your function the number of threads equal to the number of cores of your processor. If you want to tune the WorkerPool settings by yourself, pass them as second argument to workerify function:

const asyncFn = workerify(fn, {
  count: 4,
});

Basic usage of WorkerPool

In this example, work with the worker on the "request-response" principle will be demonstrated.

Project structure:

. your-project-directory
└── node_modules
└── index.js
└── worker.js

index.js:

const path = require('path');
const WorkerPool = require('worker-union');

const pool = new WorkerPool({
  path: path.resolve('worker.js'), // absolute path to worker source code
  count: 1,
});

pool.start();

pool.send('ping').then(response => console.log(response));

worker.js

const Worker = require('worker-union/worker');

new Worker((message) => {
  console.log('Received message:', message);

  return 'pong';
});

Result:

node --experimental-worker index.js
# -> pong

Another WorkerPool example

And in this example it will be shown that the worker can send messages to the main thread without requests.

Project structure:

. your-project-directory
└── node_modules
└── index.js
└── worker.js

index.js:

const path = require('path');
const WorkerPool = require('worker-union');

const pool = new WorkerPool({
  path: path.resolve('worker.js'),
  count: 1,
  eventHandler: message => console.log(`Recieved message from worker: ${message}`),
});

pool.start();

// we doesn't send any data here

worker.js

const Worker = require('worker-union/worker');

const worker = new Worker();

setInterval(() => worker.emit('Hello!'), 1000); // send 'Hello' to main thread every second

Result:

node --experimental-worker index.js
# -> Received message from worker: Hello!
# -> Received message from worker: Hello!
# -> Received message from worker: Hello!
# -> Received message from worker: Hello!

Advanced features

A description of all the features of the library, such as automatic thread allolocation, shared-memory state etc., will be ready soon. Stay tuned!

License

MIT.