0

I'm currently having a node.js script running on my Raspberry PI running Raspbian. That node.js script gets started at boot so I just have to plug in the board.

But, if the script would crash resulting in the exit of node, how could I make the boot service (which starts the node script at bood) auto restart itself when the node service crashed?

Here's an example of my bootservice in /etc/init.d:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          MyScriptService
# Required-Start:    $all
# Required-Stop:     
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts my node.js script.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

case "$1" in
  start)
    log_begin_msg "Starting my script"

    node /home/pi/myscript.js

    log_end_msg $?
    exit 0
    ;;
  stop)
    log_begin_msg "Stopping my script"


    log_end_msg $?
    exit 0
    ;;
  *)
    exit 1
    ;;
esac

UPDATE: Been able to fix it myself within Node itself. https://stackoverflow.com/a/50413860/3037607

Mason
  • 1,007
  • 1
  • 13
  • 31

2 Answers2

2

You probably should run your script with pm2 which is a process manager for node applications, it will restart your node program if it crashes up to a certain number of restarts.

Once you have pm2 installed change the following line on your init.d script

node /home/pi/myscript.js

to it:

pm2 start /home/pi/myscript.js

You'll also get some other niceties, like start/stop/restart your app with pm2 and some logging so you can backtrace why your app is crashing.

E. Celis
  • 717
  • 7
  • 17
  • Thanks for your answer, I did found a solution myself within node itself. But I'll keep your answer in mind when using services which only run native linux scripts. – Mason May 18 '18 at 14:44
0

After searching a bit deeper in the Node possibilities I found a way to just not make the script crash, and if an exception is not caught, just restart everything:

process.on('uncaughtException', function(err){
  console.log(err);
  restartMyScript();  
});
Mason
  • 1,007
  • 1
  • 13
  • 31