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

promise-worker-node

v2.0.0

Published

Communicate with a Web Worker using Promises on Node

Downloads

8

Readme

promise-worker-node Build Status Coverage Status

Modified version of promise-worker library to run on node.js. The original does work on node.js in general but is not designed to support it, and doesn't handle some error cases that could happen on node (which this library intends to handle).

A small and performant library for communicating with Web Workers, using Promises. Post a message to the worker, get a message back.

Goals:

  • Tiny footprint (~2.5kB min+gz)
  • Assumes you have a separate worker.js file (easier to debug, better browser support)
  • JSON.stringifys messages for performance

Live examples:

Usage

Install:

npm install promise-worker

Inside your main bundle:

// main.js
var PromiseWorker = require('promise-worker-node');
var worker = new Worker('worker.js');
var promiseWorker = new PromiseWorker(worker);

promiseWorker.postMessage('ping').then(function (response) {
  // handle response
}).catch(function (error) {
  // handle error
});

Inside your worker.js bundle:

// worker.js
var registerPromiseWorker = require('promise-worker-node/register');

registerPromiseWorker(function (message) {
  return 'pong';
});

Note that you require() two separate APIs, so the library is split between the worker.js and main file. This keeps the total bundle size smaller.

If you prefer script tags, you can get PromiseWorker via:

<script src="https://unpkg.com/promise-worker/dist/promise-worker.js"></script>

And inside the worker, you can get registerPromiseWorker via:

importScripts('https://unpkg.com/promise-worker/dist/promise-worker.register.js');

Message format

The message you send can be any object, array, string, number, etc.:

// main.js
promiseWorker.postMessage({
  hello: 'world',
  answer: 42,
  "this is fun": true
}).then(/* ... */);
// worker.js
registerPromiseWorker(function (message) {
  console.log(message); // { hello: 'world', answer: 42, 'this is fun': true }
});

Note that the message will be JSON.stringifyd, so you can't send functions, Dates, custom classes, etc.

Promises

Inside of the worker, the registered handler can return either a Promise or a normal value:

// worker.js
registerPromiseWorker(function () {
  return Promise.resolve().then(function () {
    return 'much async, very promise';
  });
});
// main.js
promiseWorker.postMessage(null).then(function (message) {
  console.log(message): // 'much async, very promise'
});

Ultimately, the value that is sent from the worker to the main thread is also stringifyd, so the same format rules apply.

Error handling

Any thrown errors or asynchronous rejections from the worker will be propagated to the main thread as a rejected Promise. For instance:

// worker.js
registerPromiseWorker(function (message) {
  throw new Error('naughty!');
});
// main.js
promiseWorker.postMessage('whoops').catch(function (err) {
  console.log(err.message); // 'naughty!'
});

Note that stacktraces cannot be sent from the worker to the main thread, so you will have to debug those errors yourself. This library does however, print messages to console.error(), so you should see them there.

Multi-type messages

If you need to send messages of multiple types to the worker, just add some type information to the message you send:

// main.js
promiseWorker.postMessage({
  type: 'en'
}).then(/* ... */);

promiseWorker.postMessage({
  type: 'fr'
}).then(/* ... */);
// worker.js
registerPromiseWorker(function (message) {
  if (message.type === 'en') {
    return 'Hello!';
  } else if (message.type === 'fr') {
    return 'Bonjour!';
  }
});

Browser support

This library is designed to run in Node.js, and is a fork of a library that does run in browsers. Technically this probably does run in browsers, but that's not the goal here. I'd recommend the original if you don't specifically need the extra node bits that this library adds.

API

Main bundle

new PromiseWorker(worker)

Create a new PromiseWorker, using the given worker.

PromiseWorker.postMessage(message)

Send a message to the worker and return a Promise.

  • message - object - required
    • The message to send.
  • returns a Promise

Worker bundle

Register a message handler inside of the worker. Your handler consumes a message and returns a Promise or value.

registerPromiseWorker(function)

  • function
    • Takes a message, returns a Promise or a value.

Testing the library

First:

npm install

Then to test in Node (using an XHR/PseudoWorker shim):

npm test

Or to test manually in your browser of choice:

npm run test-local

Or to test in a browser using SauceLabs:

npm run test-browser

Or to test in PhantomJS:

npm run test-phantom

Or to test with coverage reports:

npm run coverage