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

hello-worker

v1.3.4

Published

A library for quickly using web worker in browser.

Downloads

2

Readme

Hello Worker

A library for quickly using web worker in browser. It is not designed for node side, just for browser side.

Install

npm install hello-worker

or

<script src="dist/hello-worker.js"></script>

Usage

ES6:

import HelloWorker from 'hello-worker/src/hello-worker'

With pack tools like webpack:

import HelloWorker from 'hello-worker'

CommonJS:

const HelloWorker = require('hello-worker')

AMD & CMD:

define(['hello-worker'], function(HelloWorker) {
  // use HelloWorker
})

Normal Browsers:

const HelloWorker = window['hello-worker']

To use:

const computer = new HelloWorker(`
  function(arg1, arg2) {
    // compute
    return result
  }
`)
// ...
computer.invoke(data1, data2).then(res => {}).catch(e => {})
// ...
computer.invoke(data3, data4).then(res => {}).catch(e => {})

The core idea is use new to create a computer with passed function. And then use this computer to calculate with different parameters.

Methods

constructor([dependencies,] factory)

When you new an instance, you should pass a function as a string into constructor. This function can be called 'algorithm', later you will use it to calculate different variables to get results.

In worker, you can not use global window default. But here in HelloWoker factory, you can use window as global self.

dependencies

dependencies is optional.

Script files which to be import into worker script. In webworker, we use importScripts to import script files. You should pass script files url array as dependencies:

const computer = new HelloWorker(['/hello-type/dist/hello-type.js'], `function(num) {
  const { Type, HelloType } = window['hello-type']
  const NumberType = new Type(Number)
  HelloType.expect(num).toMatch(NumberType)

  return num + 1
}`)

Here, I import hello-type by import url '/hello-type/dist/hello-type.js', and in the function, than you can use HelloType.

invoke(...args)

Invoke the 'algorithm' function and pass parameters into it. invoke method return a promise, so you can use then or use in async function.

async function() {
  let res = await computer.invoke(data)
  // ...
} ()

close()

Destory the computer. After close, invoke will throw error.

watch(callback)

Different from invoke, in invoke .then only run once when the worker thread call back, in watch the callback function will run at each time the worker thread call back, so you can use regular loop in worker script.

let factory = `function() {
  setInterval(() => fetch('http_url').then($notify), 10*60*1000)
}`
let listener = new HelloWorker(factory)
listener.watch(function(data) {
  console.log(data)
})

Then you will find callback function passed into watch will be run at each time when $notify called.

NOTICE: When you use watch, the factory function is called 'watcher', you should NOT pass parameters into it and should NOT invoke invoke anymore. In fact, you should make sure that the script function should be run in worker only once. So how to pass args? Just use it you your script string:

let factory = `function() {
  let a = ${a}; // use 'a' here
  let time = ${Date.now()}; // pass time
}`

Remember to use .close() to release it when your component will unmount.

static run(factory, ...args)

To run a function in a worker only once, you can use this static method:

let factory = `
  function(arg1, arg2) {
    // ...
  }
`
HelloWorker.run(factory, data1, data2).then(res => {
  // ...
})

You do not need to close the worker by yourself, run method will close the worker when resolved.

$notify && $throw

I provide $notify and $throw functions in your 'algorithm' function, so that you can post data back to main thread anytime. $notify means send back successful data, $throw means throw out error.

let factory = `function() {
  //..
  if (wrong) {
    $throw(err) // break program here
  }
  $notify(1)
  return 2 // will not work because of $notify
}`

If you use $notify, return value in factory will be ignored. $notify has higher priority. If you use multiple $notify, only the first one will work when you use invoke, you can only receive the first notify message in your main thread, however, watch method works as you wanted.

Use $notify in situations which has async operations.

let factory = `function(url) {
  fetch(url).then(res => {
    $notify(res.json())
  })
}`

Others

After you create a worker thread, the function will not run until you call invoke. So do not invoke a worker thread factory which has setInterval too many times unless you know what you are doing.

When you post back data from worker thread to main thread, you'd better to remember that never send back with context. i.e.

// in worker factory
var e = new Obj(msg)
$notify(e) // this is wrong

The previous code will throw an error because memory is not shared between different threads.

I use blob to inject js, which make hello-worker not work in IE10. I use native Promise, so Promise polyfill needed.

If you want some referer, you can look into https://github.com/zhangyuanwei/EasyWorker which has more feature and supports node side.