Start nodejs script during bootup on your RPi

If you have written a nodejs script you want to be able to run this application as a daemon on your linux system. For this purpose you could use Forever. The purpose of Forever is to keep a child process (such as your node.js web server) running continuously and automatically restart it when it exits unexpectedly. In this article you can find how to install forever and launch a nodejs script in init.d.

Installation

sudo npm -g install forever

Command Line Usage
You can use forever to run scripts continuously (whether it is written in node.js or not).
Start:

forever start server.js
Output:
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info:    Forever processing file: server.js

Stop:

forever stop server.js
Output:
info:    Forever stopped process:
    uid  command             script    forever pid   id logfile                 uptime
[0] MKqv /usr/local/bin/node server.js 19915   19920    /root/.forever/MKqv.log 0:0:1:14.969

Start script during boot
To start your script during boot on your raspbian you will need to create a script in /etc/init.d. In this example I will use a script called nodestart to which you can provide two arguments “start” and “stop”. The nodejs script is called “server.js”.

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

export PATH=$PATH:/usr/local/bin
export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules

case "$1" in
  start)
  exec forever --sourceDir=/[directory to your script] -p /[log directory] server.js
  ;;
stop)
  exec forever stopall
  ;;
*)
  echo "Usage: /etc/init.d/nodeup {start|stop}"
  exit 1
  ;;
esac

exit 0

Your almost there! Make the script executable and install it:

chmod 755 /etc/init.d/nodestart
update-rc.d nodeup defaults

Now it will be automatically started during boot or you can try it via the CLI:

/etc/init.d/nodestart start

You can remove the script via:

update-rc.d -f nodestart remove

Install nodejs on RPi2

Unfortunately nodejs is no longer maintained via an installation of apt-get install on the raspberry PI. Please use below instructions for the installation.

Be sure that you first remove the old one:

sudo apt-get remove nodejs

Then check on the nodejs site the latest version: https://nodejs.org/dist/latest/
In my case it is: node-v6.0.0-linux-armv7l.tar.gz

For the RPi1 use should use armv6l.tar.gz

Now it’s time to download and install.

wget https://nodejs.org/dist/latest/node-v6.0.0-linux-armv7l.tar.gz
tar -xvf node-v6.0.0-linux-armv7l.tar.gz 
cd node-v6.0.0-linux-armv7l
sudo cp -R * /usr/local/

Your done! Now check that it is working by node -v