Get your own Node server
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
  // Keep track of http requests
  let numRequests = 0;
  
  // Create two workers
  const worker1 = cluster.fork();
  const worker2 = cluster.fork();
  
  // Count requests
  function messageHandler(msg) {
    if (msg.cmd && msg.cmd === 'notifyRequest') {
      numRequests += 1;
      console.log(`Total requests: ${numRequests}`);
    }
  }
  
  // Listen for messages from workers
  worker1.on('message', messageHandler);
  worker2.on('message', messageHandler);
  
  // Send periodic messages to workers
  setInterval(() => {
    // Send a message to both workers
    worker1.send({ cmd: 'updateTime', time: Date.now() });
    worker2.send({ cmd: 'updateTime', time: Date.now() });
  }, 5000);

} else {
  // Worker process
  
  // Track the last update time
  let lastUpdate = Date.now();
  
  // Receive messages from the primary
  process.on('message', (msg) => {
    if (msg.cmd && msg.cmd === 'updateTime') {
      lastUpdate = msg.time;
      console.log(`Worker ${process.pid} received time update: ${new Date(lastUpdate)}`);
    }
  });
  
  // Create an HTTP server
  http.createServer((req, res) => {
    // Notify the primary about the request
    process.send({ cmd: 'notifyRequest' });
    
    // Respond to the request
    res.writeHead(200);
    res.end(`Hello from Worker ${process.pid}. Last update: ${new Date(lastUpdate)}\n`);
  }).listen(8000);
  
  console.log(`Worker ${process.pid} started`);
}

              
Worker 8624 started
Worker 31896 started
Worker 31896 received time update: Wed Jun 18 2025 08:17:38 GMT+0200 (sentraleuropeisk sommertid)
Worker 8624 received time update: Wed Jun 18 2025 08:17:38 GMT+0200 (sentraleuropeisk sommertid)
Worker 31896 received time update: Wed Jun 18 2025 08:17:43 GMT+0200 (sentraleuropeisk sommertid)
Worker 8624 received time update: Wed Jun 18 2025 08:17:43 GMT+0200 (sentraleuropeisk sommertid)
Worker 8624 received time update: Wed Jun 18 2025 08:17:48 GMT+0200 (sentraleuropeisk sommertid)
Worker 31896 received time update: Wed Jun 18 2025 08:17:48 GMT+0200 (sentraleuropeisk sommertid)
Worker 8624 received time update: Wed Jun 18 2025 08:17:53 GMT+0200 (sentraleuropeisk sommertid)
Worker 31896 received time update: Wed Jun 18 2025 08:17:53 GMT+0200 (sentraleuropeisk sommertid)
Total requests: 1
Total requests: 2
Worker 31896 received time update: Wed Jun 18 2025 08:17:58 GMT+0200 (sentraleuropeisk sommertid)
Worker 8624 received time update: Wed Jun 18 2025 08:17:58 GMT+0200 (sentraleuropeisk sommertid)