Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

Open
@Hi-Pyncho

Description

@Hi-Pyncho

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions