javascriptnode.jsmultithreadingworker-threadnode-worker-threads

create worker file (worker threads nodejs)


I want to create a worker to send back an array as response to my main file, but I can't understand why the worker is not sending postMessage to main. Here is some dummy code to explain

My main file:

const { Worker } = require('worker_threads')
const worker = new Worker('./workerFile.js')

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

My workerFile.js

this.postMessage('hello world!')

Solution

  • I had to import parentPort and then use it in workerFile.js:

    const { parentPort } = require('worker_threads')
    parentPort.postMessage('hello world!')