Home > Software engineering >  create worker file (worker threads nodejs)
create worker file (worker threads nodejs)

Time:05-03

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

CodePudding user response:

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

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