InterProcessCommunication icon indicating copy to clipboard operation
InterProcessCommunication copied to clipboard

question: what difference between es6 modules and commonJS when working with clusters and processes?

Open Hi-Pyncho opened this issue 2 years ago • 0 comments

@tshemsedinov, hi! when i practiced with clusters, i faced with es6 modules problem

there is a peace of code (i taked your code, maked it more simple and placed to one file) (use node 18.12.1)

// import cluster from 'node:cluster';
const cluster = require('node:cluster');

if(cluster.isPrimary) {
  console.log('Started master:', process.pid);

  const worker = cluster.fork();
  console.log('Started worker:', worker.process.pid);

  console.log('sending message from server')
  worker.send('hello from server');

  worker.on('message', (message) => {
    console.log('message from worker', worker.process.pid, message);

    process.exit(0);
  });

  setTimeout(() => process.exit(1), 5000);
}

if(cluster.isWorker) {
  console.log('Worker is ready ', process.pid, cluster.worker.id);

  process.on('message', (message) => {
    console.log('message from server ', process.pid, message);

    process.send('hello from worker');
  });
}

when i use commonJS, it's worked fine. but if i use es6 modules - it doesn't work as i expect

here es6 module console output:

// Started master: 2468
// Started worker: 10064
// sending message from server
// Worker is ready  10064 1

and commonJS console output

// Started master: 2388
// Started worker: 12760
// sending message from server
// Worker is ready  12760 1
// message from server  12760 hello from server
// message from worker 12760 hello from worker

i think it happened because new worker process created asynchronously when i use es6 modules. and i need wait for worker message to make sure, that i can send messages to this worker. i saw issues (like this) with this problem in node, and i want to know your opinion. is there another simpler solutions for this problem?

thank you in advance!

Hi-Pyncho avatar Apr 23 '23 13:04 Hi-Pyncho