Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hi-Pyncho opened this issue Apr 23, 2023 · 0 comments

Comments

@Hi-Pyncho
Copy link

Hi-Pyncho commented Apr 23, 2023

@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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant