Missing1984
Missing1984

Reputation: 49

restart nodejs server programmatically

User case: My nodejs server start with a configuration wizard that allow user to change the port and scheme. Even more, update the express routes

Question: Is it possible to apply the such kind of configuration changes on the fly? restart the server can definitely bring all the changes online but i'm not sure how to trigger it from code.

Upvotes: 2

Views: 2345

Answers (2)

iG Cloud
iG Cloud

Reputation: 47

I know this question was asked a long time ago but since I ran into this problem I will share what I ended up doing.

For my problem I needed to restart the server since the user is allowed to change the port on their website. What I ended up doing is wrapping the whole server creation (https.createServer/server.listen) into a function called startServer(port). I would call this function at the end of the file with a default port. The user would change port by accessing endpoint /changePort?port=3000. That endpoint would call another function called restartServer(server,res,port) which would then call the startServer(port) with the new port then redirect user to that new site with the new port.

Much better than restarting the whole nodejs process.

Upvotes: 0

alandarev
alandarev

Reputation: 8635

Changing core configuration on the fly is rarely practiced. Node.js and most http frameworks do not support it neither at this point.

Modifying configuration and then restarting the server is completley valid solution and I suggest you to use it. To restart server programatically you have to execute logics outside of the node.js, so that this process can continue once node.js process is killed. Granted you are running node.js server on Linux, the Bash script sounds like the best tool available for you.

Implementation will look something like this:

  1. Client presses a switch somewhere on your site powered by node.js
  2. Node.js then executes some JavaScript code which instructs your OS to execute some bash script, lets say it is script.sh
  3. script.sh restarts node.js
  4. Done

If any of the steps is difficult, ask about it. Though step 1 is something you are likely handling yourself already.

Upvotes: 3

Related Questions