In NodeJS documentation, the Worker constructor looks like it requires a path to a file that contains the code to execute on the new worker thread.
It's something like:
const encode_worker = new Worker(`./service-encode.js`, { workerData: config });
My question is if it's possible to pass in a string rather than a file for the Worker? The reason I'm asking is due to how our main app is built and launched from its host application.
For example, is it possible to do
const encode_worker = new Worker(`console.log("Hello World")`, { workerData: config });
If so, how can we handle multiline strings for this?
Expanding on Niilo's answer, this is how I use the
{ eval: true }
Worker mode:The idea is to use
Function.toString()
to get a more elegantly built worker code snippet, and have your worker code actually validated, transpiled and linted as normal JS would.Beware that code in the
workerFn
arrow function above cannot access any externally scoped variables from the main thread, including having torequire
modules again within the worker thread.