Export functions or class into a worker context in nodejs and web browser. Tasks are cancellable.
$ npm i @tbela99/workerizethe
import{workerize,dispose}from"@tbela99/workerize";// do node stuffimport{workerize,dispose}from"@tbela99/workerize/web";// do browser stuffAlternatively, you can use the 'browser.js' script which uses the UMD module format.
<scriptsrc="dist/browser.js"></script><script>constfunc=workerize.workerize(function(){// do something})</script>The function is turned into an async proxy.
import{workerize,dispose}from"@tbela99/workerize/web";// async and arrow functions can be passed as well constfunc=workerize(function(...args){returnargs.reduce((acc,curr)=>acc+curr,0);});response=awaitfunc(1,2,70);// 74// terminate the service workerdispose(func);All class methods are turned into async proxies.
import{workerize,dispose}from"@tbela99/workerize";// pass a class definitionconstClass=workerize(class{type;name;age;constructor(type,age,name=''){this.type=type;this.age=age;this.name=name;if(name===''){letnumber=Math.floor(3+3*Math.random());while(number--){this.name+=String.fromCharCode([65,97][Math.floor(2*Math.random())]+Math.floor(26*Math.random()))}}}say(){return`${this.name} says: I am a ${this.age} year(s) old ${this.type}`;}});// create an instance constdog=newClass('Dog',2,'Marvin');console.log(awaitdog.say());// 'Marin says: I am a 2 years(s) old Dog'// terminate the service workerdispose(dog);You can inject javascript libraries into the worker context.
import{workerize,dispose}from"@tbela99/workerize";constfunc=workerize(function(...args){// sum function is defined in ./js/sum.jsreturnsum(...args);},{dependencies: ['./js/sum.js']});constresult=awaitfunc(5,43,10);console.log(result);// 58dispose(func);import{workerize,dispose}from"@tbela99/workerize";constfunc=workerize(function(...args){// an array called 'modules' containing the declared modules is injected in the scope// modules are in the same order they are declared// add is exported by the module ./js/add.jsreturnmodules[0].add(...args);},{dependencies: ['./js/add.js'],module: true});constresult=awaitfunc(5,43,10);console.log(result);// 58dispose(func);parameters:
- task: function or class to execute in the worker context.
- options: optional, worker options.
worker options:
- dependencies: array. an array of javascript files to inject as module or dependencies
- module: boolean. If true, dependencies are injected as modules. A variable of type array called 'modules' will be injected in the scope. it contains the injected modules in the same order as they were injected.
- signal: optional. AbortSignal instance used to abort the worker execution and delete it
Delete the worker instance.
dispose(worker1[,worker2, ...,workern]);All parameters you pass to the proxy must be transferable. Objects will be serialized and deserialized as JSON data. All methods, property settter and getter are removed.
MIT OR LGPL-3.0
Thanks to Jetbrains for providing a free WebStorm license