Created
October 17, 2018 10:17
-
-
Save morsh/15a321df3b091e4514c8216e9835bea0 to your computer and use it in GitHub Desktop.
Example on how to run multi-process node.js server
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 is sample to show multiprocess programming in node.js | |
*/ | |
const cluster = require('cluster'); | |
const http = require('http'); | |
const numberOfCPUs = require('os').cpus().length; | |
if (cluster.isMaster) { | |
// Fork workers. | |
for (let i = 0; i < numberOfCPUs; i++) { | |
cluster.fork(); | |
} | |
// Wait for workers to die, then display a message | |
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 | |
const server = http.createServer((req, res) => { | |
res.writeHead(200); | |
res.end(`Hello world from worker #${cluster.worker.id}`); | |
}).listen(8000, () => { | |
console.log(`Worker #${cluster.worker.id} is listening on port 8000`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment