24

How to restart Node.js server from code? For example, if using expressjs framework,

app.get('/restart', function (req, res, next) {
//Code to restart a server
})

I want to restart server from app like this, without going to console etc. How to do it?

3 Answers 3

29

I use forever in order to start and monitoring application. So the restart function like this:

app.get('/restart', function (req, res, next) {
  process.exit(1);
});

After the shutdown of server, forever will restart service.

console:

Express server listening on port 3000 in development mode
error: Forever detected script exited with code: 1
error: Forever restarting script for 2 time
Express server listening on port 3000 in development mode
Sign up to request clarification or add additional context in comments.

1 Comment

But who will monitor and restart forever itself in case it crashes or hangs?
1

By combining npm restart and child_process.exec() it appears possible to restart the server programmatically. And since it allows for several scripts to be run for stopping, restarting, and starting this option would work even for multi-process servers or otherwise complex servers where simply calling process.exit() isn't viable.

3 Comments

an example would be great and allow future reader to better understand your answer
Any example of how would that work? The point of child_process is that it's a child process and shutting down the parent process will also shut down the child process, so you can't have the child process boot back up the parent process.
@undefined You can mark a child-process as detached which I believe makes it survive past the parent's destruction. So if you use that, with a "sleep" command at the start of the command (in case concurrent running is an issue), it should work.
1

You can mark a child-process as detached which I believe makes it survive past the parent's destruction. So if you use that, with a "sleep" command at the start of the command (in case concurrent running is an issue), it should work.

So presumably something like this (untested):

const newProcessInstance = spawn(process.argv[0], process.argv.slice(1), {
  detached: true,
  stdio: 'ignore', // not sure if this is needed
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.