Skip to content

Instantly share code, notes, and snippets.

@kenji4569
Created December 16, 2022 04:37
Show Gist options
  • Save kenji4569/b74cf04ce34cb8f2ab5a1923ac4fe367 to your computer and use it in GitHub Desktop.
Save kenji4569/b74cf04ce34cb8f2ab5a1923ac4fe367 to your computer and use it in GitHub Desktop.
import express from 'express'
import cluster from 'cluster'
import { cpus } from 'os'
import process from 'process'
const workers = Math.min(Number(process.argv[2]) || 1, cpus().length)
const blockTime = Number(process.argv[3])
const app = express()
const port = 4000
app.get('/', (req, res) => {
if (blockTime) {
const now = new Date()
while(new Date() - now < blockTime) {}
}
res.send('Hello World')
})
if (cluster.isPrimary) {
console.log(`🚀 Listening on port ${port}`)
console.log(`Number of cpus: ${cpus().length}`)
console.log(`Number of workers: ${workers}`)
if (blockTime) {
console.log(`Block time milliseconds: ${blockTime}`)
}
console.log(`Primary ${process.pid} is running`)
for (let i = 0; i < workers; i++) {
cluster.fork()
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`)
})
} else {
await new Promise((resolve) => app.listen({ port }, resolve))
console.log(`Worker ${process.pid} started`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment