worker-provider
v2.1.0
Published
a manager for worker
Downloads
4
Maintainers
Readme
WorkerProvider
Usage
const wp = new WorkerProvider('./worker/path.js');
wp.on('channelName', (payload) => {
console.log(payload);
});
// send one message to idle workers
wp.send({
channel: 'channelName',
payload: 'anydata'
});
// destory it
wp.destroy();
// if your browser support transferable object
if (WorkerProvider.isTransferablesSupported()) {
const transferableObj = new Uint8Array(1);
wp.send({
channel: 'channelName',
payload: transferableObj
}, [ transferableObj.buffer ]);
}
// if you need make a worker to do some thing
var yourAction = WorkerProvider.asyncFnMover(function calc(data) {
var payload = data.payload;
var channel = data.channel;
payload++;
return Promise.resolve({
channel: channel,
payload: payload
});
};
const wp1 = new WorkerProvider(yourAction);
wp1.on('plus1', (payload) => {
console.log(payload);
});
wp1.send({
channel: 'plus1',
payload: 1
});
declaration
import { EventEmitter } from "events";
export interface MyWorker {
buzy: boolean;
instance: Worker;
}
export interface WorkerMessage {
channel: string;
payload?: any;
}
export declare type WorkerMessages = [WorkerMessage, Transferable[]?];
export interface WorkersProvider extends EventEmitter {
workers: MyWorker[];
cpus: number;
messages: WorkerMessages[];
onmessage(e: MessageEvent): void;
send(message: WorkerMessage, transfer?: Transferable[]): void;
run(): void;
destroy(): void;
removeMessage(message: WorkerMessage): void;
removeMessagesByChannel(channel: string): void;
}
export default class WorkerProvider extends EventEmitter implements WorkersProvider {
static isTransferablesSupported(): boolean;
static asyncFnMover(fn: (data: WorkerMessage) => Promise<WorkerMessage>): string;
workers: MyWorker[];
cpus: number;
messages: WorkerMessages[];
constructor(workerPath: string);
onmessage(e: MessageEvent): void;
run(): void;
send(message: WorkerMessage, transfer?: Transferable[]): void;
destroy(): void;
removeMessage(message: WorkerMessage): void;
removeMessagesByChannel(channel: string): void;
}