expressjsHow do I use Express.js to create a cluster?
Express.js is a web framework for Node.js. It can be used to create a cluster of multiple processes that can run on multiple CPU cores. To create a cluster with Express.js, the cluster
module must be used. Here is an example of how to create a cluster with Express.js:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log('Master process is running');
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Worker ' + cluster.worker.id);
});
app.listen(8000);
console.log(`Worker ${cluster.worker.id} is running`);
}
This example will create a cluster of numCPUs
workers and run an Express.js server on each one. The server will respond to requests with the message Hello from Worker <worker id>
.
Code explanation
const cluster = require('cluster');
- This imports thecluster
module from Node.js.const numCPUs = require('os').cpus().length;
- This gets the number of CPUs available on the system.if (cluster.isMaster) {...} else {...}
- This checks if the process is the master process. If so, it will fork workers. Otherwise, it will run the Express.js server.cluster.fork()
- This is used to fork a worker process.const express = require('express');
- This imports the Express.js module.const app = express();
- This creates an Express.js app.app.get('/', (req, res) => {...});
- This sets up a route that will respond to requests with the messageHello from Worker <worker id>
.app.listen(8000);
- This starts the Express.js server on port8000
.
For more information on how to use Express.js to create a cluster, please refer to the following links:
More of Expressjs
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js to make an XHR request?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use express-zip js to zip and download files?
- How do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How do I use Zod with Express.js?
- How do I use Express.js to parse YAML files?
- How can I use Express.js to yield results?
- How do I use adm-zip with Express.js?
See more codes...