Skip to content

Instantly share code, notes, and snippets.

@mykeels
Created April 4, 2018 09:13
Show Gist options
  • Select an option

  • Save mykeels/483f2cbb41f7916780eb9d24bfbc0edd to your computer and use it in GitHub Desktop.

Select an option

Save mykeels/483f2cbb41f7916780eb9d24bfbc0edd to your computer and use it in GitHub Desktop.
Fork of index.js in https://gist.github.com/mykeels/8396f87d42a809697d08f6b6c9cd8db0 showing how clusters can be used
const cluster = require('cluster')
const os = require('os')
const express = require('express')
const isPrime = require('./is-prime')
if (cluster.isMaster) {
const cpuCount = os.cpus().length
for (let i = 0; i < cpuCount; i++) {
cluster.fork()
}
}
else {
const app = express()
app.get('/', (req, res) => {
const primes = []
const max = Number(req.query.max) || 1000
for (let i = 1; i <= max; i++) {
if (isPrime(i)) primes.push(i)
}
res.json(primes)
})
const port = process.env.PORT || 3030
app.listen(port)
console.log('app is running on port', port)
}
cluster.on('exit', (worker) => {
console.log('mayday! mayday! worker', worker.id, ' is no more!')
cluster.fork()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment