audreyt / node-webworker-threads

Lightweight Web Worker API implementation with native threads
https://npmjs.org/package/webworker-threads
Other
2.3k stars 149 forks source link

Webworker inline string #162

Open danielepolencic opened 7 years ago

danielepolencic commented 7 years ago

I had a quick look at the source code and it's not possible to use a string to create a WebWorker:

new Worker(`
function(){
  postMessage("I'm working before postMessage('ali').");
  this.onmessage = function(event) {
    postMessage('Hi ' + event.data);
    self.close();
  };
}
`)

The reason why this is interesting is because you could use browserify to compile typescript/livescript files and inline them in the webworker (with all the imports and requires resolved).

The browser API has a similar functionality:

var blob = new Blob([
    "onmessage = function(e) { postMessage('msg from worker'); }"]);

// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);

var worker = new Worker(blobURL);
worker.onmessage = function(e) {
  // e.data == 'msg from worker'
};
worker.postMessage(); // Start the worker.

I had a quick look at the code and it should be feasible to detect if the input is a Buffer and load the content as a web worker.

Any thoughts?

audreyt commented 7 years ago

Makes sense, pull reqs welcome at src/worker.ls.

Given the current code base, would new Worker(eval(string)) work too?

wagenaartje commented 7 years ago

This is exactly what I need... I want to construct workers from strings that are dynamically created at run-time.

MeirionHughes commented 7 years ago

It would be nice to have this natively supported so that it is consistent with the browser behavior (blob url)