23.03.2020 Views

node-js

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13: Cluster Module

Syntax

• const cluster = require("cluster")

• cluster.fork()

• cluster.isMaster

• cluster.isWorker

• cluster.schedulingPolicy

• cluster.setupMaster(settings)

• cluster.settings

• cluster.worker // in worker

• cluster.workers // in master

Remarks

Note that cluster.fork() spawns a child process that begins executing the current script from the

beginning, in contrast to the fork() system call in C which clones the current process and

continues from the instruction after the system call in both parent and child process.

The Node.js Documentation has a more complete guide to clusters here

Examples

Hello World

This is your cluster.js:

const cluster = require('cluster');

const http = require('http');

const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {

// Fork workers.

for (let i = 0; i < numCPUs; i++) {

cluster.fork();

}

cluster.on('exit', (worker, code, signal) => {

console.log(`worker ${worker.process.pid} died`);

});

} else {

// Workers can share any TCP connection

// In this case it is an HTTP server

require('./server.js')();

}

This is your main server.js:

https://riptutorial.com/ 58

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!