Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including mole-rpc-transport-webworker with all npm packages installed. Try it out:

mole-rpc-transport-webworker lists no main file and has no index.js, so it can't be directly required. If this is a mistake, please let us know. It may however contain internal files that you can require manually:

require("mole-rpc/package.json"); // mole-rpc is a peer dependency. // require("mole-rpc-transport-webworker/[??]")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

mole-rpc-transport-webworker v1.0.2

Easy way to communicate with webworker using Mole-RPC (JSON RPC library)

Webworker Transport for Mole RPC (JSON RPC Library)

npm version Build Status Known Vulnerabilities

Offload intensive calculations to WebWorker with just several lines of code.

Mole-RPC is a tiny transport agnostic JSON-RPC 2.0 client and server which can work both in NodeJs, Browser, Electron etc.

This is WebWorker based transport but there are many more transports.

What is the reason of using JSON-RPC for WebWorkers?

People usually send data to WebWorker in a form like {id, method, params} in JSON format via postMessage. As a result they expect {id, result}. And this is what JSON RPC is. id is required when you send several request and need to map results and requests.

So, why to write own solution every time? This transport allows you use JSON RPC for calling methods in WebWorkers. Moreover, it will handle all of edge-cases like errors processing, timeouts, batch calls, bidirectional communication etc.

Mole-RPC has zero dependencies and is a very small library.

Usage example (with simplified API)


import expose from 'mole-rpc-transport-webworker/expose';

const sum = (a, b) => a + b;
const multiply = (a, b) => a * b;

expose({ sum, multiply }).catch(console.error);


import createClient from 'mole-rpc-transport-webworker/createClient';

async function main() {
  const client = createClient(new Worker('worker.js'));
  const result = await client.sum(2, 3);

main().then(console.log, console.error);

You can pass extra Mole-RPC options to createClient as second parameter.

For example

const client = createClient(new Worker('worker.js'), { 
  requestTimeout: 1000 

More examples

Simple API for sending work to your web worker (recommended).

See examples/simple-send-work-to-webworker

Standard API for sending work to your web worker.

See examples/send-work-to-webworker

Bidirectional connection

Each side works as client and server the same time.

See examples/bidirectional-calls

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free