Sorry if I completely do not understand some basics.
Today a friend ask me why some code works with worker_threads module well but the similar code works with cluster module weirdly. I am not much proficient in both modules, but, in a quick digging, I've found out some unexpectedness in the cluster work: if cluster.fork() happens in the module code, it forks both module and parent script. Is this an expected and documented behavior? Or is this some basics related self-evident stuff?
Reduced example:
parent.js:
'use strict';
const cluster = require('cluster');
console.log(`${__filename} is master: ${cluster.isMaster}`);
const f = require('./child.js');
f();
child.js:
'use strict';
const cluster = require('cluster');
console.log(`${__filename} is master: ${cluster.isMaster}`);
if (cluster.isMaster) {
module.exports = function f() {
cluster.fork();
console.log('ok');
};
} else {
// ...
}
Output:
parent.js is master: true
child.js is master: true
ok
parent.js is master: false
child.js is master: false
parent.js:9
f();
^
TypeError: f is not a function
at Object.<anonymous> (parent.js:9:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:236:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
Do you expect that the fork only executes child.js?
Yes. Sorry)
@vsemozhetbyt It's expected and documented here: https://nodejs.org/dist/latest-v10.x/docs/api/cluster.html#cluster_cluster_settings
The default worker file is process.argv[1]. If you do cluster.settings.exec = __filename from the master in child.js, you'll get the result you want.
Thank you!
I should add that cluster.setupMaster({ exec: __filename }) is the recommended way to set the settings.