top of page
Logo der Online Agentur mdwp

Node.js Cluster

Node.js Cluster is not a term exclusive to React JS - rather, it's a feature of Node.js, which is a runtime environment for executing JavaScript code on the server side. Nevertheless, Node.js Cluster is pertinent for running React JS apps efficiently on the server side.

A Node.js Cluster is a group of Node.js processes that run simultaneously and work together to distribute the workload. By default, Node.js is single-threaded, which means it only runs on one core of our server. However, modern servers have multiple cores. This is where the Cluster module becomes useful. It allows you to create child processes (workers), which can run on different cores of your server, enabling your application to handle more load by taking full advantage of multi-core systems.

Here is a simple code snippet in Node.js that utilizes the Cluster module:

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

if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
```

In this code, cluster.fork() is used to create child processes. The 'isMaster' property is used to identify if the current process is the master process. When this property is true, the application knows it has to create new workers.

bottom of page