1'use strict'; 2 3const http = require('http'); 4const cluster = require('cluster'); 5 6function handleRequest(request, response) { 7 response.end('hello world\n'); 8} 9 10const NUMBER_OF_WORKERS = 2; 11var workersOnline = 0; 12 13if (cluster.isMaster) { 14 cluster.on('online', function() { 15 if (++workersOnline === NUMBER_OF_WORKERS) { 16 console.error('all workers are running'); 17 } 18 }); 19 20 process.on('message', function(msg) { 21 if (msg.type === 'getpids') { 22 const pids = []; 23 pids.push(process.pid); 24 for (var key in cluster.workers) 25 pids.push(cluster.workers[key].process.pid); 26 process.send({ type: 'pids', pids: pids }); 27 } 28 }); 29 30 for (var i = 0; i < NUMBER_OF_WORKERS; i++) { 31 cluster.fork(); 32 } 33} else { 34 const server = http.createServer(handleRequest); 35 server.listen(0); 36} 37