Hello World

suggest change

This is your cluster.js:

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

// Node 16+ prefers cluster.isPrimary. cluster.isMaster still works.
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:

const http = require('http');

function startServer() {
    const server = http.createServer((req, res) => {
      res.writeHead(200);
      res.end('Hello Http');
    });

    server.listen(3000);
}

if(!module.parent) {
    // Start server if file is run directly
    startServer();
} else {
    // Export server, if file is referenced via cluster
    module.exports = startServer;
}

This example hosts a basic web server and forks workers (child processes) with the built-in cluster module. The number of forked processes depends on the number of CPU cores. A single Node.js process runs JavaScript on one thread, so the workers let the application use more than one core. Every worker listens on port 3000. The primary process distributes connections round-robin by default, except on Windows, where the default scheduling policy is SCHED_NONE.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents