create worker file (worker threads nodejs)

908 views Asked by At

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!')
1

There are 1 answers

0
DepletedKnowledge On BEST ANSWER

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

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