Last active
August 18, 2019 23:22
-
-
Save caesaneer/75154ee728c9068b06ad2460fb2661bd to your computer and use it in GitHub Desktop.
Part 2 - Node Cluster Module
This file contains 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
// ════════════════════════════════════════════════════════════════════════════════════════════════╡ | |
const cluster = require('cluster') | |
const http = require('http') | |
const numCPUs = require('os').cpus().length | |
const bench = require('./bench') | |
// ════════════════════════════════════════════════════════════════════════════════════════════════╡ | |
const host = '192.168.0.14' | |
const port = 8000 | |
const start = async function startServer() { | |
// Cluster | |
if (cluster.isMaster) { | |
console.log(`Master ${process.pid} is running.`) | |
// Run cluster.fork based on numCPUs | |
for (let i = 0; i < numCPUs; i += 1) { | |
cluster.fork() | |
} | |
cluster.on('exit', (worker, code, signal) => { | |
console.log(`A worker with ID ${worker.process.pid} died.`) | |
}) | |
} else { | |
// Simple request router | |
const router = function requestRouter(request, reply) { | |
const result = bench(100) | |
reply.end('OK') | |
} | |
// Start HTTP server | |
const server = http.createServer(router) | |
server.listen(port, host, () => { | |
console.log(`Node.js Standard Library HTTP server running on port: ${port}`) | |
}) | |
} | |
} | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment