Home > other >  How can you set up a nodejs web server to run asynchronously?
How can you set up a nodejs web server to run asynchronously?

Time:06-24

Okay, so I'm in the process of creating a Minecraft panel. I have a windows service, and that will call my express server. The problem is, that when the computer tries to start the process, it goes on infinitely because the server will run for eternity. I need this to be changed so that when it runs it will start up the web server, make sure it's running, and then finish the task and forget the webserver exists, but leave it running. How would this be possible? Many thanks :)

Update: After a little bit of though I'm going to refine my question to this: How can I start a process and not wait for it to finish in C#/nodejs(either work)

Edit: Lol i am refreshing this page like every two microseconds.... Its 4 AM for me so yeah :D brain - broke

CodePudding user response:

Answer: So I figured out how to fix it. I used pm2 which can start a process and not wait for it to finish. We have a start.js and a stop.js which can start it. If you want to build something like it here is the code I used.

//Start.js
const pm2 = require('pm2');

pm2.connect((err) => {
  if (err) {
    console.log(err);
  } 
});

pm2.start({
  name: 'webserver',
  script: "webserver.js",
}, (err) => {
  if (err) {
    console.log(err)
  } else {
    console.log('Webserver started');
    pm2.disconnect();
    process.exit(0)
  }
})
//Stop.js
const pm2 = require('pm2');

//Stop the webserver 
pm2.stop('webserver', (err) => {
  if (err) {
    console.log(err);
  } else {
    console.log('Webserver stopped');
    pm2.disconnect();
    process.exit(0)
  }
});
  • Related