trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Multi threading with hyper-express #14

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

Use the cluster module in Node.js to multi-thread HyperExpress instances to have them handle their own payloads similar to all other webservers.

// NOTE: Any global code/variables will be executed for both the master and forked worker processes
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const HyperExpress = require('hyper-express');

// Check if the current process is the master process
if (cluster.isPrimary) {
   // NOTE: Code inside of this block will only run ONCE in the master/primary process

   // Spawn the initial set of worker instances which will be decided based on the number of cpu cores available
   for (let i = 0; i < numCPUs; i++) cluster.fork();
} else {
   // NOTE: Code inside of this block will run for each time a worker is forked with the fork() method from the master process.

   // Initialize the HyperExpress server instance
   const server = new HyperExpress.Server();

   // Bind a test route which will return the process id in which it is serving the request from
   server.get('/id', (request, response) => {
      response.send('Served this request from ' + process.pid);
   });

   // Listen the server on the desired port
   server.listen(3000);
}

Source: https://github.com/kartikk221/hyper-express/discussions/78#discussioncomment-2926141