Skip to content

cluster: cluster in a module #21814

@vsemozhetbyt

Description

@vsemozhetbyt
  • Version: 10.6.0 (all?)
  • Platform: Windows (all?)
  • Subsystem: cluster

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    clusterIssues and PRs related to the cluster subsystem.moduleIssues and PRs related to the module subsystem.questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions