0%

nodejs-cluster

API

cluster.js

1
2
const childOrPrimary = 'NODE_UNIQUE_ID' in process.env ? 'child' : 'primary';
module.exports = require(`internal/cluster/${childOrPrimary}`);

primary.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
const cluster = new EventEmitter();
module.exports = cluster;

...

cluster.isWorker = false;
cluster.isMaster = true; // Deprecated alias. Must be same as isPrimary.
cluster.isPrimary = true;
cluster.Worker = Worker;
cluster.workers = {};
cluster.settings = {};
cluster.SCHED_NONE = SCHED_NONE; // Leave it to the operating system.
cluster.SCHED_RR = SCHED_RR; // Primary distributes connections.

...

child.js

1
2
3
4
5
6
7
8
9
10
11
12
13
const cluster = new EventEmitter();
const handles = new SafeMap();
const indexes = new SafeMap();
const noop = FunctionPrototype;

module.exports = cluster;

cluster.isWorker = true;
cluster.isMaster = false; // Deprecated alias. Must be same as isPrimary.
cluster.isPrimary = false;
cluster.worker = null;
cluster.Worker = Worker;

Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const cluster = require('cluster')

console.log("-----------------------------")
if (cluster.isMaster) {
console.log("master")
const worker = cluster.fork();
console.log(process.pid)
worker.send('hi there');

} else if (cluster.isWorker) {
console.log("worker")
process.on('message', (msg) => {
// process.send(msg);
console.log(msg)
console.log(process.pid)
});
}
1
2
3
4
5
6
7
-----------------------------
master
41914
-----------------------------
worker
hi there
41915