DEV Community

muckitymuck
muckitymuck

Posted on

Simple Express server

demo:simpleServer

const express = require('express') // including the express library
const app = express() // creating an express application instance
const port = 3123 // setting the port for the app to run on

const cluster = require('cluster') // including the cluster library
const numCPUs = require('os').cpus().length; // getting the number of CPU available on the machine

if (cluster.isMaster) {
  console.log(`Master ${process.pid} 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 {
  // this is where the code will trigger
  const clientid = ''
  if (cluster.isWorker){
    console.log(`Client ID: ${cluster.worker.id} running`)
    const clientid = cluster.worker.id
  }
}

const bodyParser = require("body-parser"); // including the body-parser library
app.use(bodyParser.json()); // using json body parser for the app

const timestamp = new Date().toISOString(); // getting the timestamp for each request

app.get('/', (req, res) => {
    console.log(`OK: ${timestamp}`) // logging the timestamp of the request

    console.log(`data received: ${JSON.stringify(req.body)}`) // logging the data received in the request
    console.log(`${clientid}:${timestamp}:${req.body}`) // logging the clientid, timestamp and data received
    res.send(`OK: ${timestamp}`) // sending a response to the client

})
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*"); // allowing all origin to access the server
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // allowing certain headers
    next();
});
app.post('/', ( req, res ) => {
    console.log(req.body) // logging the data received in post request
    res.json({
        message: `OK ${new Date().toISOString()}`, // sending back a message with the current timestamp
        data: req.body // sending back the data received in the request
    });
})

app.listen(port, () => {
    console.log(`example app listening on port ${port}`) // logging that the server is listening on a specific port
})
Enter fullscreen mode Exit fullscreen mode

AI Generated:

In this code, we are using the cluster module in Node.js to create a cluster of worker processes that listen on the same port and handle incoming requests. The cluster module allows for easy creation of child processes that share server ports, which can greatly improve the performance of a Node.js application.

The first thing we do is require the cluster and os modules. Then, we use os.cpus().length to get the number of CPU cores on the machine, which we will use to determine how many worker processes to create.

Next, we check if the current process is the master process using cluster.isMaster. If it is, we log that the master process is running and then use a for loop to create worker processes equal to the number of CPU cores. We also set up an event listener for when a worker process exits, which logs the worker's process ID.

If the current process is not the master process, we then set a variable clientid to be an empty string. Then we check if the process is a worker with cluster.isWorker. If it is, we log that the worker process with the corresponding ID is running and set clientid to be the worker's ID.

After that, we use the body-parser middleware to parse the incoming request body as JSON. Then, we set up routes for handling GET and POST requests to the server. For GET requests, we log the timestamp and any data received in the request body. For POST requests, we log the request body and send a JSON response containing a message with the current timestamp and the data received in the request.

Finally, we have the server listen on the specified port.

In short, this code is using the Node.js cluster module to create worker processes and listening on the same port to handle incoming requests. This helps improve performance by allowing multiple requests to be handled simultaneously. The code also logs the worker ID and any data received in the request body. This can be useful for debugging and keeping track of which worker is handling which requests.

Top comments (0)