Workers run in separate threads within the same process and can share memory using SharedArrayBuffer. Cluster creates separate Node.js processes, each with its own memory space.
Workers run in separate threads allowing CPU-intensive tasks to run in parallel without blocking the main event loop. Cluster creates separate processes but does not share memory, which can add overhead.
const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { for (let i = 0; i < 4; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.end('Hello World'); }).listen(8000); }
Each cluster worker runs as a separate process with its own memory space, so total memory usage is the sum of all workers' memory. This can cause high memory use compared to threads.
The Worker class is imported from 'worker_threads' and instantiated with the new keyword and the path to the worker script.
const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { cluster.fork(); cluster.fork(); } else { http.createServer((req, res) => { res.end(`Handled by worker ${process.pid}`); }).listen(3000); console.log(`Worker ${process.pid} started`); }
The cluster module allows multiple worker processes to listen on the same port. The master distributes incoming connections among workers, enabling load balancing.