
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
A simple RPC layer for communicating with web workers and over other transports
The worker-rpc package is a lightweight and efficient library for facilitating RPC (Remote Procedure Call) style communication between web workers and the main thread in a web environment. It simplifies the process of sending and receiving messages, making it easier to manage asynchronous tasks and parallel processing in web applications.
Creating an RPC Provider
This code sample demonstrates how to create an RPC provider in the main thread. The RpcProvider is initialized with a function that sends messages to the worker. The worker's onmessage handler is set to dispatch incoming messages through the RpcProvider.
const { RpcProvider } = require('worker-rpc');
const rpcProvider = new RpcProvider(message => worker.postMessage(message));
worker.onmessage = event => rpcProvider.dispatch(event.data);
Creating an RPC Handler
This code sample shows how to set up an RPC handler inside a worker. It creates an RpcProvider that sends messages back to the main thread. The 'calculate' RPC handler is registered to multiply a number by 2, demonstrating how to handle specific tasks.
const { RpcProvider } = require('worker-rpc');
const rpcProvider = new RpcProvider(message => postMessage(message));
onmessage = event => rpcProvider.dispatch(event.data);
rpcProvider.registerRpcHandler('calculate', data => data.num * 2);
Comlink is a popular library that abstracts the communication between web workers and the main thread, making it appear as if you are calling an object method directly. Compared to worker-rpc, Comlink provides a more object-oriented approach, which might be more intuitive for developers familiar with object-oriented programming.
Threads.js offers a high-level abstraction over web workers and also supports Node.js workers. It allows for easy creation of multithreaded applications and manages the complexity of thread communication. Unlike worker-rpc, which focuses on message passing, threads.js provides a more comprehensive solution for multithreading, including thread pooling and error handling.
This package provides a simple RPC mechanism on top of any transport that transfers
JSON data. It was initially conceived to provide communication with web workers
(and as such supports transferables), but it can be used on top of many other
different transport channels, i.e. postMessage
between frames, websockets via
socket.io
or JSON encoded messages over pipes.
You can install the library into your project via npm
npm install worker-rpc
The library is written in Typescript and will work in any environment that supports ES5 and ES6-style promises (either native or through a shim). No external typings are required for using this library with Typescript (version >= 2).
In this example, we use the library to set up communication with a web worker.
import {RpcProvider} from 'worker-rpc';
const rpcProvider = new RpcProvider(
(message, transfer) => postMessage(message, transfer)
);
onmessage = e => rpcProvider.dispatch(e.data);
rpcProvider.registerRpcHandler('add', ({x, y}) => x + y);
The RPC provider is initialized with a function that dispatches a message. This function will receive an opaque message object as first argument, and a list of transferables as second argument. This allows to leverage transfer of ownership instead of copying between worker and host page.
On incoming messages, dispatch
is called on the RPC provider in order to
handle the message.
Each registered RPC handler is identified by a message ID (add
in this example)
and has a handler function that receives the message object and can return a
result either as an immediate value or as a promise.
import {RpcProvider} from 'worker-rpc';
const worker = new Worker('worker.js'),
rpcProvider = new RpcProvider(
(message, transfer) => worker.postMessage(message, transfer)
);
worker.onmessage = e => rpcProvider.dispatch(e.data);
rpcProvider
.rpc('add', {x: 1, y: 2})
.then(result => console.log(result)); // 3
ES5 / CommonJS
var RpcProvider = require('worker-rpc').RpcProvider;
ES6
import {RpcProvider} from 'worker-rpc';
Typescript
import {RpcProvider, RpcProviderInterface} from 'worker-rpc';
The API is built around the RpcProvider
class. A RpcProvider
acts both as
client and server for RPC calls and event-like signals. The library uses ES6
promises and can consume any A+ compliant promises.
const rpc = new RpcProvider(dispatcher, timeout);
dispatcher
: A function that will be called for dispatching messages. The
first argument will be an opaque message object, and the second argument
an error of Transferable
objects that are to be passed via ownership
transfer (if supported by the transport).timeout
(optional): The timeout for RPC transactions in milliseconds.
Values of 0
or smaller disable the timeout (this is the default).rpc.dispatch(message);
Similar to message dispatch, worker-rpc
does not provide a built-in mechanism
for receiving messages. Instead, incoming messages must be relayed to the provider
by invoking dispatch
.
message
: The received message.rpc.registerRpcHandler(id, handler);
Register a handler function for RPC calls with id id
. Returns the provider instance.
id
: RPC call id. Only a single handler can be registered for any id. Ids should
be strings.handler
: The handler function. This function receives the payload object as
its argument and can return its result either as an immediate value or as a
promise.rpc.registerSignalHandler(id, handler));
Register a handler function for signals with id id
. Returns the provider instance.
id
: Signal id. The namespace for signal ids is seperate from that of RPC ids,
and multiple handlers my be attached tp a single signal. Ids should be stringshandler
: The handler function. This function receives the payload object as
its argument; the result is ignored.const result = rpc.rpc(id, payload, transfer);
Dispatch a RPC call and returns a promise for its result. The promise is rejected if the call times out or if no handler is registered (or if the handler rejects the operation).
id
: RPC call id.payload
(optional): RPC call payload.transfer
(optional): List of Transferables
that will be passed to dispatched
(see above).rpc.signal(id, payload, transfer);
Dispatch a signal. Returns the provider instance.
id
: Signal id.payload
(optional): Signal payload.transfer
(optional): List of Transferables
that will be passed to dispatched
(see above).rpc.deregisterRpcHandler(id, handler);
id
and handler
must be the same arguments used for registerRpcHandler
.
Returns the provider instance.
rpc.deregisterSignalHandler(id, handler);
id
and handler
must be the same arguments used for registerSignalHandler
.
Returns the provider instance.
rpc.error.addHandler(errorHandler);
The error event is dispatched if there is either a local or remote communcation error (timeout, invalid id, etc.). Checkout the microevent.ts documentation for the event API.
Feel free to use this library under the conditions of the MIT license.
0.2.0
Cleanup and modernization changes. There is a minor change in the typings that should not cause any breakage (handler args are not optional any more).
FAQs
A simple RPC layer for communicating with web workers and over other transports
The npm package worker-rpc receives a total of 2,144,693 weekly downloads. As such, worker-rpc popularity was classified as popular.
We found that worker-rpc demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.