Junior — Middle
How can working with multiple threads or processes be implemented in Node.js to improve performance?
sobes.tech AI
Answer from AI
In Node.js, there are several approaches to work with multiple threads or processes:
clustermodule — allows creating multiple worker processes that can handle requests in parallel, utilizing all CPU cores. Each worker is a separate process with its own event loop.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker ' + process.pid);
}).listen(8000);
}
- Worker Threads (
worker_threads) — allow creating threads within a single process that can perform CPU-intensive tasks in parallel without blocking the main event loop.
const { Worker } = require('worker_threads');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.postMessage('Hello from worker thread');
`, { eval: true });
worker.on('message', message => console.log(message));
- External processes (
child_process) — can launch separate processes and communicate with them via IPC.
The choice depends on the task: for server scaling, cluster is better; for computations, worker_threads.