The cluster module is a feature available in Node.js that allows you to create separate processes which can run simultaneously. This capability helps to handle the load on a networked Node.js application and makes it suitable for multi-core systems.
These separate processes can share the same server port and are spawned using the .fork() method in Node.js. Each child process runs on its own V8 engine environment and has a separate memory space. They communicate with the parent master process through IPC and pass server handles back and forth.
Here’s an example of how to use the cluster module:
```
var cluster = require(‘cluster’);
var http = require(‘http’);
var numCPUs = require(‘os’).cpus().length; // Get the number of CPUs available
if (cluster.isMaster) {
console.log(‘Master process is running, PID:’, process.pid); // Fork workers for each CPU for (var 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 http.createServer((req, res) => { res.writeHead(200); res.end(‘Hello world\n’); }).listen(8000);}
```
In this code, a server is created for each CPU in the system. If a worker dies or disconnects, the ‘exit’ event is listened for and the console will log that the worker process has died.
This allows a Node.js web server to take advantage of multi-core systems, improving performance and robustness.
Keep in mind that Node.js is single-threaded, so for CPU-bound tasks (like image processing or heavy computations), the cluster module may not bring performance improvements.