@pythiacorporation/rpc-node
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

@wexond/rpc-node

Type-safe communication between message ports from Node.js worker_threads module.

NPM NPM

Installation

$ npm install --save @wexond/rpc-node @wexond/rpc-core

Quick start

Here's an example of communication from the main thread to a worker_thread:

  • Create a file that is imported in both the worker_thread and the main thread, for example ping-pong.ts:
import { WorkerChannel } from '@wexond/rpc-node';

export interface PingPongService {
  ping(): string;
}

export const pingPongChannel = new WorkerChannel<PingPongService>('ping-pong');
  • Code for your worker_thread:
import { RpcWorkerHandler } from '@wexond/rpc-node';
import { PingPongService, pingPongChannel } from './ping-pong';

class PingPongHandler implements RpcWorkerHandler<PingPongService> {
  // Equivalent of |parentPort.on('message')|
  ping(): string {
    return 'pong';
  }
}

// |parentPort| is the default value for the |messagePort| parameter in |getReceiver|.
pingPongChannel.getReceiver().handler = new PingPongHandler();
  • Code for the main thread:
import { resolve } from 'path';
import { Worker } from 'worker_threads';

import { pingPongChannel } from './ping-pong';

const worker = new Worker('path/to/worker.js');
const pingPongService = pingPongChannel.getInvoker(worker);

(async () => {
  console.log(await pingPongService.ping()); // Prints `pong`.
})();

More examples

Documentation

WIP

Readme

Keywords

none

Package Sidebar

Install

npm i @pythiacorporation/rpc-node

Weekly Downloads

0

Version

1.0.4

License

none

Unpacked Size

12 kB

Total Files

20

Last publish

Collaborators

  • pythia-inc