@zlepper/worker-threads-rpc
Provides a connection implementation for NodeJS' worker_threads
.
Installation
First install the library:
npm install --save @zlepper/rpc @zlepper/worker-threads-rpc
Usage
This sample shows how to implement a simple calculator that runs in a worker thread.
Start by creating the actual class that has the logic that should be run in your worker:
export class Calculator {
public add(a: number, b: number): number {
return a + b;
}
public subtract(a: number, b: number): number {
return a - b;
}
}
Next create the worker initialization code:
import { startWorkerProvider } from '@zlepper/rpc';
import { WorkerThreadServerConnection } from '@zlepper/worker-threads-rpc';
import { parentPort } from 'worker_threads';
import { Calculator } from './calculator';
if (parentPort) {
const connection = new WorkerThreadServerConnection(parentPort);
startWorkerProvider(new Calculator(), connection);
}
Lastly in your main thread: Start the worker and connect to it:
import { wrapBackgroundService } from '@zlepper/rpc';
import { WorkerThreadClientConnection } from '@zlepper/worker-threads-rpc';
import { Worker } from 'worker_threads';
import { Calculator } from './calculator';
const workerThread = new Worker('./worker.js');
const connection = new WorkerThreadClientConnection(workerThread);
const wrapper = wrapBackgroundService<Calculator>(connection);
console.log(await wrapper.add(1, 2));
console.log(await wrapper.subtract(2, 1));
Also check the full sample here.