Complete the code to create a cluster that forks worker processes.
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { for (let i = 0; i < [1]; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker ' + process.pid); }).listen(8000); }
The code uses numCPUs to fork a worker for each CPU core.
Complete the code to set up a simple reverse proxy using the 'http-proxy' library.
const http = require('http'); const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer({}); const server = http.createServer((req, res) => { proxy.web(req, res, { target: [1] }); }); server.listen(8000);
The proxy target is usually a backend server, here running on port 3000 locally.
Fix the error in the cluster code to properly listen on a port in each worker.
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('Worker ' + process.pid); }).listen([1]); }
The server must listen on a numeric port like 8000, not a string or other value.
Fill both blanks to create a cluster that logs when a worker exits and forks a new one.
const cluster = require('cluster'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { for (let i = 0; i < [1]; i++) { cluster.fork(); } cluster.on('[2]', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died`); cluster.fork(); }); }
The cluster forks workers equal to numCPUs and listens for the 'exit' event to restart workers.
Fill all three blanks to create a reverse proxy that logs requests and forwards them to a backend.
const http = require('http'); const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer({}); const server = http.createServer((req, res) => { console.log('Request URL:', [1]); proxy.web(req, res, { target: [2] }); }); server.listen([3]);
The code logs the request URL, proxies to the backend at port 4000, and listens on port 8080.