user2650875 user2650875 - 4 months ago 13
Node.js Question

Start Node.js App on Boot

I'm working on a Raspberry Pi running Raspbain running a Node.js app and trying to get it to start when the Pi boots. I found a couple of examples but I can't seem to get it working. My current code is:

#! /bin/sh
# /etc/init.d/MyApp

### BEGIN INIT INFO
# Provides: MyApp.js
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts MyApp.js
# Description: Start / stop MyApp.js at boot / shutdown.
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting MyApp.js"
# run application you want to start
node /home/pi/app/MyApp/MyApp.js
;;
stop)
echo "Stopping MyApp.js"
# kill application you want to stop
killall MyApp.js
;;
*)
echo "Usage: /etc/init.d/MyApp {start|stop}"
exit 1
;;
esac

exit 0


I have this in the etc/init.d folder, ran
chmod +x /etc/init.d/MyApp
, I'm able to run it manually, then I run
sudo update-rc.d MyApp defaults
, reboot and the script never runs. I've looked at some different examples, made adjustments and still no luck.

Any help would be appreciated.

Answer

If you're using a prebuilt Pi release like 0.10.24, you may be experiencing a PATH issue.

You can either provide the full path to the node binary as part of the start command or make sure the PATH to the node binaries are set before /etc/init.d/MyApp is ran. I had the same issue and tried both with success. Also, the stop command as you have it may not be working.

#! /bin/sh
# /etc/init.d/test

### BEGIN INIT INFO
# Provides:          test
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting test.js"
    # run application you want to start
    #node /home/pi/test.js > /home/pi/test.log
    /home/pi/downloads/node-v0.10.24-linux-arm-pi/bin/node /home/pi/test.js >> /home/pi/test.log
   ;;
   stop)
    echo "Stopping test.js"
    # kill application you want to stop
    killall -9 node
    # Not a great approach for running
    # multiple node instances
    ;;
  *)
    echo "Usage: /etc/init.d/test {start|stop}"
    exit 1
    ;;
esac

exit 0

If you'd like to do sudo node, you can add the PATH to Defaults secure_path using sudo visudo.

Also, I would recommend using something like forever to keep your process running after crashes and what not.

Comments