Harry
Harry

Reputation: 55019

Call function inside worker thread nodejs

Here's my worker:

const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct

I would like to call hello()

How do I do this?

Upvotes: 5

Views: 3534

Answers (2)

hieumc
hieumc

Reputation: 1

you can use worker-messenger on npm to write that style:

import { Worker } from 'worker_threads'
import { ParentMessenger } from 'worker-messenger'
const test = async () => {
    const results = await messenger.callWorker('testFunction_2', 'args', timeout)
    console.log({results});
}
test()

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075497

Threads communicate through passing messages back and forth, for instance:

worker.postMessage("say hello");

Your worker would set up a listener for the message event, and receive the message as the value property of that eevnt:

// In the worker
const { isMainThread, parentPort } = require('worker_threads');
if (!isMainThread) {
    parentPort.on("message", e => {
        // Dispatch here. For instance:
        if (e.value === "say hello") {
            hello();
        }
    };
}
function hello() { /*...*/ }

There's a lot more to messaging back and forth, details in the worker documentation.

Upvotes: 5

Related Questions