@vonage/js-workerizer
v1.2.3
Published
Library providing a simple way to run a class instance on its dedicated worker.
Downloads
4,364
Maintainers
Readme
js-workerizer
Library providing a simple way to run a class instance on its dedicated worker.
Table of content
Installation
Requirements
Installation
# Install dependencies
npm install @vonage/js-workerizer
Running example
# from the example/basic directory
npm install
npm run dev
Quick start
Short example
import { MyWorkerizableClass } from "./my-workerizable-class.ts";
import Worker from "./my-workerizable-class.ts?worker&inline";
const onMainThread = new MyWorkerizableClass();
onMainThread.doSomething(); // run on the main thread
const onAWorker = await workerize(MyWorkerizableClass, Worker);
await onMainThread.doSomething(); // run on a worker
Run a class in a worker
Imaging you want to run this class in a worker.
export class HugeProcessClass {
run() {
// ... super slow process
}
}
// Class usage
const process = new HugeProcessClass();
process.run(); // will run on the main thread
- First step is to make the class instantiable from the worker. To achieve it, you must use the registerWorker function.
We suggest to call it in the static constructor of the class. Decorator should be provided soon as typescript release them.
export class HugeProcessClass {
// ... class impl
// These lines allow the class to be used in a worker
static {
registerWorker('HugeProcessClass', this);
}
}
- Second, you need to instantiate the class as a worker using workerize function instead of new operator.
// Class usage
const process = await workerize(HugeProcessClass);
await process.run(); // will run on a worker
Terminate a worker
export class SomeClass {
// this method will be call if defined before the worker is terminated
public terminate() {
}
// These lines allow the class to be used in a worker
static {
registerWorker('HugeProcessClass', this);
}
}
// Class usage
const worker = await workerize(SomeClass);
await worker.terminate();
License
This project is licensed under the terms of the MIT license and is available for free.