Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NextJS NodeJS multi processes

I use NextJS for frontend development and NodeJS for backend development. I want to use child processes. How can I set NodeJS up. How can I use multiple processes for my NextJS application. Can anyone provide me with a sample code for it?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think you are looking for this

or,

https://stackoverflow.com/a/72831318/13086781

This is just a sample code that I wrote like 2 years ago. It should still work.

const express = require("express");
const next = require("next");
const cluster = require("cluster");
const os = require("os");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

//if the cluster is master
if (cluster.isMaster) {
  for (let i = 0; i < numCpu; i++) {
    cluster.fork();
  }

  //if worker dies or is killed
  cluster.on("exit", (worker, code, signal) => {
    cluster.fork();
  });
} else {
  app
    .prepare()
    .then(() => {
      const server = express();

      server.all("*", (req, res) => {
        return handle(req, res);
      });

      server.listen(port, (err) => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`, process.pid);
      });

    })
    .catch((ex) => {
      console.error(ex.stack);
      process.exit(1);
    });
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading