Created
April 12, 2018 10:14
-
-
Save OmisNomis/5ad2c877e60d3ba10c19fc7b40ea450d to your computer and use it in GitHub Desktop.
Express application with Node Clustering
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
'use strict'; | |
/* | |
* Highly scalable Express server | |
* Purely for example purposes, until I start the blog properly! | |
*/ | |
const cluster = require('cluster'); | |
if (cluster.isMaster) { | |
const numWorkers = require('os').cpus().length; | |
console.log('Master cluster setting up ' + numWorkers + ' workers...'); | |
for (var i = 0; i < numWorkers; i++) { | |
cluster.fork(); | |
} | |
cluster.on('online', function(worker) { | |
console.log('Worker ' + worker.process.pid + ' is online'); | |
}); | |
cluster.on('exit', function(worker, code, signal) { | |
console.log( | |
'Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal | |
); | |
console.log('Starting a new worker'); | |
cluster.fork(); | |
}); | |
} else { | |
const app = require('express')(); | |
app.all('/*', function(req, res) { | |
res.send('process ' + process.pid + ' says hello!'); | |
}); | |
const server = app.listen(8000, () => { | |
console.log('Process ' + process.pid + ' is listening to all incoming requests'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment