node.jsexpressworker-threadnode-worker-threads

Is there any way to use parentPort.on() in worker threads in node js with server.listen()


Whenever I try to use a worker having
Worker file =>

parentPort.on('message',msg =>{
    //some code here
})

Main file =>

server.listen(3000,function(){
    console.log('Server running');
});

with a server already listening it gives this error

Error: listen EADDRINUSE: address already in use 127.0.0.1:3000
    at Server.setupListenHandle [as _listen2] (net.js:1314:16)
    at listenInCluster (net.js:1362:12)
    at GetAddrInfoReqWrap.doListen [as callback] (net.js:1499:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:68:8)
Emitted 'error' event on Worker instance at:
    at Worker.[kOnErrorMessage] (internal/worker.js:233:10)
    at Worker.[kOnMessage] (internal/worker.js:243:37)
    at MessagePort.<anonymous> (internal/worker.js:164:57)
    at MessagePort.emit (events.js:315:20)
    at MessagePort.onmessage (internal/worker/io.js:78:8)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:11:10) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '127.0.0.1',
  port: 3000
}

I have tried using MessageChannel() but it also gives same error. Could you please tell what is the cause of error and how to correct it.


Solution

  • EADDERINUSE sounds like you're trying to start a new server on the same port in both the main file and in your worker thread(s).

    You need to make sure you're not trying to start a server in the worker thread(s) or if you wanted a server in the worker threads, then they each have to be on a unique port.