Created
July 11, 2024 02:47
-
-
Save kevboutin/507c6fd8fa3fc2b7e96c9cdd6c1598ae to your computer and use it in GitHub Desktop.
Cluster mode example
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
/* This code utilizes the “cluster” module to create multiple worker processes, | |
* each handling incoming requests. This approach allows you to scale your | |
* application horizontally to handle increased traffic. Note that they all use | |
* the same port. | |
*/ | |
const cluster = require('cluster'); | |
if (cluster.isMaster) { | |
// Master process forks worker processes | |
for (let i = 0; i < numCPUs; i++) { | |
cluster.fork(); | |
} | |
} else { | |
// Worker process handles incoming requests | |
const server = http.createServer((req, res) => { | |
// ... | |
}); | |
server.listen(PORT, () => { | |
console.log(`Worker process listening on port ${PORT}`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment