Last active
April 28, 2022 08:57
-
-
Save bolorundurowb/be9bc4325cd0eb5a50a95c26b44b9b77 to your computer and use it in GitHub Desktop.
A sample Express server using the NodeJS 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 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