Is it possible to use a string for NodeJS worker thread constructor?

1.2k Views Asked by At

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?

2

There are 2 best solutions below

0
On

Expanding on Niilo's answer, this is how I use the { eval: true } Worker mode:

const { Worker } = require('worker_threads');

const workerFn = () => {
    const { parentPort } = require('worker_threads');

    parentPort.postMessage('hello');
};

const worker = new Worker(workerFn.toString().substr(6), { eval: true });

worker.on('message', msg => {
    console.log(msg);
});

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 to require modules again within the worker thread.

0
On

The following worked for me.

const {
    Worker
} = require('worker_threads');

const workerString = `
const {
    parentPort
} = require('worker_threads');

parentPort.postMessage('hello')
`

const worker = new Worker(workerString, {eval: true});
worker.on('message', msg => {
    console.log(msg)
})