Last active
July 27, 2023 06:12
-
-
Save hupptechnologies/81b4e344daf92f1c974e86f21fa0def0 to your computer and use it in GitHub Desktop.
Utilizing Node.js Cluster for Maximum CPU Efficiency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const cluster = require('cluster'); | |
| const http = require('http'); | |
| const numCPUs = require('os').cpus().length; | |
| if (cluster.isMaster) { | |
| // Master process creates worker processes | |
| for (let i = 0; i < numCPUs; i++) { | |
| cluster.fork(); | |
| } | |
| cluster.on('exit', (worker, code, signal) => { | |
| console.log(`Worker ${worker.process.pid} died`); | |
| // Create a new worker if one dies | |
| cluster.fork(); | |
| }); | |
| } else { | |
| // Workers share the same TCP connection | |
| http.createServer((req, res) => { | |
| // Request handling logic | |
| res.writeHead(200); | |
| res.end('Hello from the server!'); | |
| }).listen(3000); | |
| console.log(`Worker ${process.pid} started`); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const http = require('http'); | |
| // Normal HTTP server creation | |
| const server = http.createServer((req, res) => { | |
| // Request handling logic | |
| res.writeHead(200); | |
| res.end('Hello from the server!'); | |
| }); | |
| const port = 3000; | |
| server.listen(port, () => { | |
| console.log(`Server running on port ${port}`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment