All Projects → satya164 → Web Worker Proxy

satya164 / Web Worker Proxy

A better way of working with web workers

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Web Worker Proxy

Madelineproto
Async PHP client/server API for the telegram MTProto protocol
Stars: ✭ 1,776 (+714.68%)
Mutual labels:  hacktoberfest, proxy
Cast Sh
📟 An instance of your terminal in your browser
Stars: ✭ 151 (-30.73%)
Mutual labels:  hacktoberfest, browser
Tobab
tobab: the poor mans identity aware proxy, easy to use setup for beyondcorp in your homelab
Stars: ✭ 122 (-44.04%)
Mutual labels:  hacktoberfest, proxy
Qrcode Renderer
QR Code renderer is a dependency-free library to render QR Codes. The library makes it simple to integrate with any UI framework and comes with a prebuilt SVG renderer for the web.
Stars: ✭ 56 (-74.31%)
Mutual labels:  hacktoberfest, browser
Otoroshi
Lightweight api management on top of a modern http reverse proxy
Stars: ✭ 177 (-18.81%)
Mutual labels:  hacktoberfest, proxy
Class Logger
Boilerplate-free decorator-based class logging
Stars: ✭ 64 (-70.64%)
Mutual labels:  hacktoberfest, proxy
Cls Proxify
Logging on steroids with CLS and Proxy. Integrated with express, koa, fastify.
Stars: ✭ 132 (-39.45%)
Mutual labels:  hacktoberfest, proxy
Pizzly
The simplest, fastest way to integrate your app with an OAuth API 😋
Stars: ✭ 796 (+265.14%)
Mutual labels:  hacktoberfest, proxy
Brain.js
brain.js is a GPU accelerated library for Neural Networks written in JavaScript.
Stars: ✭ 12,358 (+5568.81%)
Mutual labels:  hacktoberfest, browser
Openlinkwith
Open the current webpage you have in another app. Magic! 🔮
Stars: ✭ 158 (-27.52%)
Mutual labels:  hacktoberfest, browser
Axios Module
Secure and easy axios integration with Nuxt.js
Stars: ✭ 998 (+357.8%)
Mutual labels:  hacktoberfest, proxy
Python Scripts
Collection of Various Python Script's.💻
Stars: ✭ 195 (-10.55%)
Mutual labels:  hacktoberfest, browser
Azure Sdk For Js
This repository is for active development of the Azure SDK for JavaScript (NodeJS & Browser). For consumers of the SDK we recommend visiting our public developer docs at https://docs.microsoft.com/en-us/javascript/azure/ or our versioned developer docs at https://azure.github.io/azure-sdk-for-js.
Stars: ✭ 872 (+300%)
Mutual labels:  hacktoberfest, browser
Webworkify Webpack
launch a web worker at runtime that can require() in the browser with webpack
Stars: ✭ 105 (-51.83%)
Mutual labels:  web-worker, browser
Defiant.js
http://defiantjs.com
Stars: ✭ 907 (+316.06%)
Mutual labels:  web-worker, browser
Pokeapi Js Wrapper
PokeAPI browser wrapper, fully async with built-in cache
Stars: ✭ 129 (-40.83%)
Mutual labels:  hacktoberfest, browser
Bpmn Js
A BPMN 2.0 rendering toolkit and web modeler.
Stars: ✭ 5,592 (+2465.14%)
Mutual labels:  hacktoberfest, browser
Webtorrent
⚡️ Streaming torrent client for the web
Stars: ✭ 25,554 (+11622.02%)
Mutual labels:  hacktoberfest, browser
Secret Agent
The web browser that's built for scraping.
Stars: ✭ 151 (-30.73%)
Mutual labels:  proxy, browser
Offline Qr Code
📱 Browser add-on allowing you to quickly generate a QR code offline with the URL of the open tab or other text!
Stars: ✭ 193 (-11.47%)
Mutual labels:  hacktoberfest, browser

web-worker-proxy

Build Status Code Coverage MIT License Version Bundle size (minified + gzip)

A better way of working with web workers. Uses JavaScript Proxies to make communcation with web workers similar to interacting with normal objects.

Why

Web workers are great to offload work to a different thread in browsers. However, the messaging based API is not very easy to work with. This library makes working with web workers similar to how you'd interact with a local object, thanks to the power of proxies.

Features

  • Access and set properties on the proxied object asynchronously, even nested ones
  • Call functions on the proxied object and receive the result asynchronously
  • Pass callbacks (limited functionality) to the worker which can be called asynchronously
  • Receive thrown errors without extra handling for serialization

Installation

npm install web-worker-proxy

or

yarn add web-worker-proxy

Usage

First, we need to wrap our worker:

// app.js
import { create } from 'web-worker-proxy';

const worker = create(new Worker('worker.js'));

Inside the web worker, we need to wrap the target object to proxy it:

// worker.js
import { proxy } from 'web-worker-proxy';

proxy({
  name: { first: 'John', last: 'Doe' },
  add: (a, b) => a + b,
});

Now we can access properties, call methods etc. by using the await keyword, or passing a callback to then:

console.log(await worker.name.first); // 'John'

// or

worker.name.first.then(result => {
  console.log(result); // 'John'
});

Accessing properties is lazy, so the actual operation doesn't start until you await the value or call then on it.

Supported operations

Accessing a property

You can access any serializable properties on the proxied object asynchronously:

// Serializable values
console.log(await worker.name);

// Nested properties
console.log(await worker.name.first);

// Even array indices
console.log(await worker.items[0]);

When accessing a property, you'll get a thenable (an object with a then method), not an normal promise. If you want to use it as a normal promise, wrap it in Promise.resolve:

// Now you can call `catch` on the promise
Promise.resolve(worker.name.first).catch(error => {
  console.log(error);
});

Adding or updating a property

You can add a new property on the proxied object, or create a new one. It can be a nested property too:

worker.thisisawesome = {};
worker.thisisawesome.stuff = 42;

Calling methods

You can call methods on the proxied object, and pass any serializable arguments to it. The method will return a promise which will resolve to the value returned in the worker. You can also catch errors thrown from it:

try {
  const result = await worker.add(2, 3);
} catch (e) {
  console.log(e);
}

The method on the proxied object can return any serializable value or a promise which returns a serializable value.

It's also possible to pass callbacks to methods, with some limitations:

  • The arguments to the callback function must be serializable
  • The callback functions are one-way, which means, you cannot return a value from a callback function
  • The callback functions must be direct arguments to the method, it cannot be nested inside an object
worker.methods.validate(result => {
  console.log(result);
});

To prevent memory leaks, callbacks are cleaned up as soon as they are called. Which means, if your callback is supposed to be called multiple times, it won't work. However, you can persist a callback function for as long as you want with the persist helper. Persisting a function keeps around the event listeners. You must call dispose once the function is no longer needed so that they can be cleaned up.

import { persist } from 'web-worker-proxy';

const callback = persist(result => {
  if (result.done) {
    callback.dispose();
  } else {
    console.log(result);
  }
});

worker.subscribe(callback);

API

create(worker: Worker)

Create a proxy object which wraps the worker and allows you to interact with the proxied object inside the worker. It can take any object which implements the postMessage interface and the event interface (addEventListener and removeListener).

proxy(object: Object, target?: Worker = self)

Proxy an object so it can be interacted with. The first argument is the object to proxy, and the second argument is an object which implements the postMessage interface and the event interface, it defaults to self. It returns an object with a dispose method to dispose the proxy.

There can be only one proxy active for a given target at a time. To proxy a different object, we first need to dispose the previous proxy first by using the disposed method.

persist(function: Function)

Wrap a function so it can be persisted when passed as a callback. Returns an object with a dispose method to dispose the persisted function.

Browser compatibility

The library expects the Proxy and WeakMap constructors to be available globally. If you are using a browser which doesn't support these features, make sure to load appropriate polyfills.

The following environments support these features natively: Google Chrome >= 49, Microsoft Edge >= 12, Mozilla Firefox >= 18, Opera >= 36, Safari >= 10, Node >= 6.0.0.

Limitations

  • Since workers run in a separate thread, all operations are asynchronous, and will return thenables
  • The transferred data needs to be serializable (error objects are handled automatically), most browsers implement the structured clone algorithm for transferring data
  • The transferred data is always copied, which means the references will be different, and any mutations won't be visible

How it works

The library leverages proxies to intercept actions such as property access, function call etc., and then the details of the actions are sent to the web worker via the messaging API. The proxied object in the web worker recieves and performs the action, then sends the results back via the messaging API. Every action contains a unique id to distinguish itself from other actions.

Alternatives

Contributing

While developing, you can run the example app and open the console to see your changes:

yarn example

Make sure your code passes the unit tests, Flow and ESLint. Run the following to verify:

yarn test
yarn flow
yarn lint

To fix formatting errors, run the following:

yarn lint -- --fix
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].