I am using cluster.fork() to spawn worker processes in Node.js. I had my app functioning when all of a sudden I started getting strange errors related to the main.js file I use to startup my app being run multiple times. Here are my files:
children.js
const cluster = require('cluster');
if (cluster.isMaster) {
console.log('starting master')
const spawnWorker = function () {
let worker = cluster.fork();
return worker
}
exports.spawn = function (cnt) {
for (let i = 0; i < cnt; i++) {
console.log('spawning worker.....')
spawnWorker()
console.log('worker spawned')
}
}
}
else {
console.log('Worker activity')
}
main.js
console.log('Main called')
global.Children = require('./children');
Children.spawn(4)
console.log('Main Finished')
Output from running node main.js
Main called
starting master
spawning worker.....
worker spawned
spawning worker.....
worker spawned
spawning worker.....
worker spawned
spawning worker.....
Main called
Worker activity
After this point I get a type error that Children.spawn is not a function and it says Main Finished.
My question is, why is my main.js being called a second time? I just want it to create the worker processes which will in turn listen for events and "stop" execution after it prints "Main Finished". I appreciate any help!