0

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!

1
  • "Main called" is printed 3 more times right? Commented Mar 18, 2018 at 22:01

1 Answer 1

1

This is expected behaviour, what is forked is the whole process, not only the module from where you call cluster.fork(). Workers start their execution from the beginning of the process ;)

Your clustering module should be your main entry point.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.