Multi-process across all CPU cores

This commit is contained in:
Mars Hall
2018-02-05 21:51:32 -08:00
parent e7a5eb4ca5
commit d88e7b287c

View File

@@ -1,9 +1,26 @@
const express = require('express'); const express = require('express');
const path = require('path'); const path = require('path');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const app = express();
const PORT = process.env.PORT || 5000; const PORT = process.env.PORT || 5000;
// Multi-process to utilize all CPU cores.
if (cluster.isMaster) {
console.error(`Node cluster master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.error(`Node cluster worker ${worker.process.pid} exited: code ${code}, signal ${signal}`);
});
} else {
const app = express();
// Priority serve any static files. // Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build'))); app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
@@ -19,5 +36,6 @@ app.get('*', function(request, response) {
}); });
app.listen(PORT, function () { app.listen(PORT, function () {
console.log(`Listening on port ${PORT}`); console.error(`Node cluster worker ${process.pid}: listening on port ${PORT}`);
}); });
}