const cluster = require('cluster')
if (cluster.isMaster) {
// Creates the Forks
process.title = 'my-node-app-master'
const { length: numberOfProcs } = require('os').cpus()
for (let i = 0; i < numberOfProcs; i++) {
cluster.fork()
}
// and here you can fork again when one of the forks dies
cluster.on('exit', (worker, code, signal) => {
console.error(`worker ${worker.process.pid} died (${signal || code}). restarting it in a sec`)
setTimeout(() => cluster.fork(), 1000)
})
} else {
// run your server
const http = require('http')
process.title = 'my-node-app-fork'
http.Server((req, res) => {
res.writeHead(200)
res.end(`hello world from pid ${process.pid}
`)
}).listen(8000)
}