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-task-runner

v0.0.2

Published

Run a task inside a web worker

Downloads

4

Readme

worker-task-runner

Run a task inside a web worker

Your app can send to Web Worker a message with a script URL and data. Worker will execute the task and return the result back.

Worker uses StealJS module loader to asynchronously load the task module. Data is sent via postMessage.

The package also provides helpers for sending SharedArrayBuffer to the worker task runner. See demo demo/shared-array-task/demo.js for an example.

API

Message format

  • type message type, values are defined in src/constants.js:
    • from Worker: ready, task-result
    • to Worker: run-task
  • taskUrl {String} represents a URL to a task file that Worker will load and execute.
  • taskData {Any} data to sent to Worker to pass to the given task.
  • result {Any} contains data that worker produced as a result of executing the given task.

Helpers

  • Main:
    • create - creates a worker, returns a Task that will be resolved when the worker sends the READY event.
    • runTask - runs a task in a worker. Expects: a worker instance and a URL of a task module that will be run in the worker.
  • Utils:
    • execTask - forks a task and prints out how much time it took to execute it.
  • SharedArrayBuffer:
    • createBuffer
    • bufferToArray

Example:

worker.postMessage({
  type: "run-task",
  taskUrl: "src/my-task.js",
  taskData: [1,2,3]
})

worker.onmessage = ev => {
  if (ev.data.type === 'ready') {
    console.log('Worker is ready!')
  }
  if (ev.data.type === 'task-result') {
    console.log('Worker finished task:', ev.data.result)
  }
}

Example:

Low-level

You can use Worker directly and just use the message API

const worker = new Worker("worker-task-runner/src/worker.js")
const taskUrl = "demo/task.js"
const data = [1, 2, 3, 4]

const myCallback = result => console.log("Web worker finished: ", result)

worker.onmessage = ev => {
  if (ev.data === "ready") {
    // Send a task script URL to worker along with data. Note: type has to be `run-task`
    worker.postMessage({
      type: "run-task",
      taskUrl,
      taskData
    })
  }
  if (ev.data && ev.data.type === "task-result"){
    myCallback(ev.data.result)
  }
}

Functional-style with Tasks

You can use the following helpers to work in a functiona style using data.task's Task:

// Import helpers:
const { create, runTask, execTask } = require('worker-task-runner')

// Define your task URL and data:
const workerUrl = "worker-task-runner/src/worker.js"
const taskUrl = "demo/task.js"
const data = [1, 2, 3, 4]

// Define your main app that creates a worker and runs a task:
const app =
  create(workerUrl)
  .chain(worker => runTask(worker, taskUrl)(data))

// Execute the application (see `data.task`):
app.fork(err => console.log("Error: ", error),
         res => console.log("Result: ", res))

Or if you prefer a Promise:

// TODO :)

SharedArrayBuffer

Main app may look like this:

const { create, runTask, createBuffer, bufferToArray } = require('worker-task-runner')
const execTask = require('worker-task-runner/src/utils/exec')

// Create shared array buffer to send to worker:
const data = { buffer: createBuffer(50, 'Int32Array'), type: 'Int32Array'}

// Define the main app: create a worker and run a task:
const app =
  create('src/worker')
  .chain(worker => runTask(worker, 'demo/shared-array-task/task')(data))
  .map(bufferToArray)

// Execute the application (see `data.task`):
execTask(app)

The worker task may look like:

const Task = require('data.task')
const { bufferToArray } = require('worker-task-runner')

// testTask :: a -> Task b
const testTask = ({ buffer, type }) =>
  new Task((reject, resolve) => {

    // Convert the buffer array to a typed array:
    let array = bufferToArray({ buffer, type })

    // Do some actions that will update the buffer array:
    array.forEach((a, i) => array[i] = i * 3)

    // Resolve the task:
    resolve({ buffer, type })
  })

module.exports = testTask

Release Notes

  • 0.0.2 Helpers and demo for using SharedArrayBuffer. Also define the helpers module to be package's main script.
    • createBuffer
    • bufferToArray
  • 0.0.1 Initial version:
    • Send data via postMessage.
    • Worker loads the given task script using StealJS module loader.
    • Helpers for using data.task Task.