INNER CODE UNIT · JavaScript
setupWorkerProcesses
eldimious/nodejs-api-showcase · src/common/utils/workerProcesses/index.js:7
const setupWorkerProcesses = () => {
// to read number of cores on system
const numCores = os.cpus().length;
const workers = [];
logging.info(`Master cluster setting up ${numCores} workers`);
// iterate on number of cores need to be utilized by an application
// current example will utilize all of them
for (let i = 0; i < numCores; i++) {
// creating workers and pushing reference in an array
// these references can be used to receive messages from workers
workers.push(cluster.fork());
// to receive messages from worker process
workers[i].on('message', (message) => logging.info(`worker message: ${message}`));
}
// process is clustered on a core and process id is assigned
cluster.on('online', (worker) => logging.info(`Worker ${worker.process.pid} is online`));
cluster.on('listening', (worker) => logging.info(`Worker ${worker.process.pid} is listening`));