JavaScript utility to create a universal WebWorker from a function
$ npm install inline-worker
constructor(func: function, [ self: object ]): Worker | InlineWorker
const InlineWorker = require("inline-worker");
let self = {};
let worker = new InlineWorker(function(self) {
self.onmessage = function(e) {
postMessage(self.bark(e.data)); // (2) hello!!
};
// worker internal function
self.bark = function(msg) {
return msg + "!!";
};
}, self);
worker.onmessage = function(e) {
console.log(e.data + "!!"); // (3) hello!!!!
};
worker.postMessage("hello"); // (1)
What is worker
instance?
if (global.window === global) {
assert(worker instanceof Worker); // in the borwser
} else {
assert(worker instanceof InlineWorker); // in the node.js
}
You can test worker internal functions via self
.
assert(self.bark("bye") === "bye!!");
MIT