nodejs cluster example

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

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // 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
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

4.25
8

                                    import http, { Server } from 'http'
import cluster, { Worker } from 'cluster'
import { cpus, CpuInfo } from 'os'
import consola from 'consola'
import chalk from 'chalk'
import app from './src/app'

const coreThread: CpuInfo[] = cpus()

if (cluster.isMaster) {
	for (let i = 0; i &lt; coreThread.length; i++) {
		cluster.fork()
	}

	const workersTread: any = []
	for (const id in cluster.workers) {
		workersTread.push(id)
	}

	workersTread.forEach(
		async (pid: number, _: number): Promise&lt;void&gt; =&gt; {
			await cluster.workers[pid].send({
				from: 'isMaster',
				type: 'SIGKILL',
				message: 'cleanup is worker dead and change to new worker'
			})
		}
	)

	if (process.env.NODE_ENV !== 'production') {
		cluster.on('online', (worker: Worker): void =&gt; {
			if (worker.isConnected()) {
				console.info(`${chalk.greenBright('worker active pid')}: ${worker.process.pid}`)
			}
		})

		cluster.on('exit', (worker: Worker, code: number, signal: string): void =&gt; {
			if (worker.isDead()) {
				console.info(`${chalk.redBright('worker dead pid')}: ${worker.process.pid}`)
			}
			cluster.fork()
		})
	}
} else {
	const server = http.createServer(app) as Server
	const host: any = process.env.HOST
	const port: any = process.env.PORT
	server.listen(port, host, (): void =&gt; consola.success(`server is running on ${port}`))
}

4.25 (8 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
cluster model in node js how to implement node cluster cluster node meaning what is require(cluster) in nodejs what cluster module does in nodejs clustering of nodejs cluster methods node js how node cluster works nodejs methods of the cluster module cluster module nodejs commands how to control cluster in node js is clustering good node js cluster module method nodejs how cluster works in nodejs what are cluster modules in node js node js with cluster cluster nodejs tutorial how to use cluster in nodejs what is use of cluster in nodejs cluster methods + nodejs how node js cluster works cluster.on in node js what is a cluster in Node.js nodejs cluster who developed cluster in nodejs setup node js cluster node js clustering create a node cluster what is a node in a cluster what is a cluster in node nodejs cluster module methods nodejs cluster module example cluster module in node js sample application cluster node.js what cluster did in nodejs cluster module functions node js what is clustering in node js create node js cluster server connecting your cluster nodejs node.js cluster module how to use a cluster in node js nodejs clustering example why nodejs cluster node js cluster example code clustering node js tutorial node.js ClusterWS node.js clustering cluster module methods in node js what is nodejs cluster node cluster example cluster and node how to have a cluster node.js setup how to have a cluster nodes.js setup how to have a cluster node setup node cluster tutorial what is clustering in nodejs how to add node to the cluster methods of cluster module nodejs cluster nodejs' clustering node use of cluster in node js what is a node cluster nodejs cluster meaning clustering is used in node js in clustering in node JS? cluster nodejs module use cluster in node js Node.Cluster clustering node js apps what is node in cluster how to use cluster in node js when to use nodejs cluster module node cluster mode node and cluster nodejs spawn example node js cluster modules node js worker kill node js worker disconnect node js cluster fork cluster on exit when to use workers child process and cluster node methods of cluster modules in nodejs cluster javascript node cluter cluster.om(&quot;online') nodejs cluster event nodejs cluster.ismaster nodejs cluster.fork() Clustering node js cluster module supports 5 modules cluster.fork cluster method in node js clusters in node js httpserver return same pid in node js cluser node cluster process how to write to a file in cluster mode nodejs cluster master on exits callback how to create event before cluster master exits cluster api nodejs nodejs webservice cluster in node js clustering module methods in node js clustering module clustering in nodejs worker.on master nodejs port worker.on master nodejs require cluster nodejs create cluster child nodejs how to setup nodejs cluster module how to use nodejs cluster module what is cluster in node js worker.isConnected nodejs cluster project js cluster npm node cluster express js with clustering master process in nodejs how to get master process in nodejs do you create a server in each node worker nodejs 12 cluster installing package in cluster master node share node.js fork poll link master account to normal account node js node cluster package cluster module js nodejs cluster module cluster with node js cluster with nodejs cluster.on() node js + cluster module methods using cluster module node js can fire up chile process nodejs clusster worker path clustering js Node Cluster library node cluster fork is it possible to cluster multiple node processes? nodejs 16 clusters nodejs cluester what is cluster in nodejs cluster module in node js download node js cluster module Node.js Clusters node cluster module worker send node create clusters in node js cluster js closters y workers nodejs clustering in node.js when to do nodejs clustering nodejs cluster fork index clusters node cluster mode node js nodejs cluster fork cluster node processes how to check cluster effect on nodejs node js cluster realtime example node.js is it possible to cluster multiple node processes node js distributed load cluster worker why node app using 4 clusters what is cluster in node nodejs cluster on exit typescript nodejs cluster mode node.js cluster cluster node js cluster module nodejs clustering on node nodejs cluster multiple node process clustering in node js Clus[ters node.js nodejs clustering cluster module instances in nodejs setting cluster mode cluster mode in nodejs cluster in nodejs How to set up node clusters methods of cluster module cluster module in node js node js cluster api cluster multiple nodejs processes is it possible to cluster multiple node processes clustring with node js clustered processes in nodejs how to build fork feature nodejs cluster.on('online') cluster node node js cluster api purpose clustering nodejs nodejs cluster round robin npm cluster not distributing cluster nodejs benefits nodjs cluster module cluser js running node cluster nodejs cluster tutorial nodejs cluster cluster fork nodejs how do i cluster multiple node processes node clustering node js cluster node cluster node js cluster example cluster multiple node processes cluster in node js cluster nodejs example nodejs kill worker cluster nodejs nodejs cluster example
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source