Skip to content

Instantly share code, notes, and snippets.

@ndelangen
Created January 2, 2017 15:55
Show Gist options
  • Save ndelangen/8241f3eae5c242d0dc19029060f8b72f to your computer and use it in GitHub Desktop.
Save ndelangen/8241f3eae5c242d0dc19029060f8b72f to your computer and use it in GitHub Desktop.
The cluster module allows you to easily create child processes that all share server ports.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment