How to start a Node.js script in Raspbian at boot with PM2 under NVM

Install nvm and Node.js 0.10.38

I found this way (with nvm) is easier and more convenient than install the Node.js directly on Pi.

The compiling of Node.js on Pi 2 would take less than 1 hour. But Pi 1 would take a few hours. Just be patient.

The nvm will be installed at

/home/pi/.nvm 
or
~/.nvm

You can run node directly via

.nvm/v0.10.38/bin/node

PM2

Install pm2 firstly.

npm install -g pm2

Then run:

pm2 startup

Then follow the prompt

[PM2] You have to run this command as root. Execute the following command:
sudo env PATH=$PATH:/home/pi/.nvm/v0.10.38/bin pm2 startup linux -u pi

run this command in the terminal

sudo env PATH=$PATH:/home/pi/.nvm/v0.10.38/bin pm2 startup linux -u pi

Then run your script with

pm2 start your/script/path

Finally run

pm2 save //this is to let pm2 remember the running process, so start them at boot

Then you are done. Reboot the pi.

After reboot, you can use these commands to check your daemon process:

env PATH=$PATH:/home/pi/.nvm/v0.10.38/bin pm2 list
env PATH=$PATH:/home/pi/.nvm/v0.10.38/bin pm2 logs

Refer to this PM2 official doc for more information.


If you have this error

Error: EACCES, permission denied '/root/.pm2' 

during you reboot the Pi, then you need to change /etc/init.d/pm2-init.sh:

export PM2_HOME="/root/.pm2"
to
export PM2_HOME="/home/pi/.pm2" //if you login with pi

The blog could be helpful as well.