Created
November 9, 2017 17:20
-
-
Save NigelEarle/edb4d54e1ca7edf1427ed3cf637bb602 to your computer and use it in GitHub Desktop.
Node.js cluster
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) { | |
console.log(`Master ${process.pid} is running`); | |
// Fork workers. | |
for (let i = 0; i < numCPUs; i++) { | |
cluster.fork(); | |
} | |
cluster.on('exit', (worker, code, signal) => { | |
console.log(`worker ${worker.process.pid} died`); | |
}); | |
} else { | |
// Workers can share any TCP connection | |
// In this case it is an HTTP server | |
http.createServer((req, res) => { | |
res.writeHead(200); | |
res.end('hello world\n'); | |
}).listen(8000); | |
console.log(`Worker ${process.pid} started`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment