Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@OmisNomis
Created April 12, 2018 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OmisNomis/5ad2c877e60d3ba10c19fc7b40ea450d to your computer and use it in GitHub Desktop.
Save OmisNomis/5ad2c877e60d3ba10c19fc7b40ea450d to your computer and use it in GitHub Desktop.
Express application with Node Clustering
'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