Skip to content

Instantly share code, notes, and snippets.

@bolorundurowb
Last active April 28, 2022 08:57
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 bolorundurowb/be9bc4325cd0eb5a50a95c26b44b9b77 to your computer and use it in GitHub Desktop.
Save bolorundurowb/be9bc4325cd0eb5a50a95c26b44b9b77 to your computer and use it in GitHub Desktop.
A sample Express server using the NodeJS cluster module
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const cluster = require('cluster');
const os = require('os');
const routes = require('./routes/Routes');
if (cluster.isMaster) {
const cpuCount = os.cpus().length;
for (let i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
} else {
const app = express();
const router = express.Router();
const port = process.env.PORT || 3000;
app.use(morgan('dev'));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
routes.route(router);
app.use('/v1/', router);
app.use('/', express.static('public'), (req, res) => {
res.status(200).sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port, () => console.log(`Server started on ${port}`));
}
cluster.on('exit', function (worker) {
console.log('Worker %d died :(', worker.id);
cluster.fork();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment