Add nvm-managed node to $PATH in init.d or crontab

in Development


When I was using node installed via apt-get, a simple NODE=$(which node) was enough.

However, once I switched to the nvm-based node, it was no longer installed in one of the $PATH locations where the system is looking. So the correct path had to be added manually.

One option is to hardcode whatever the current node path is, but that means the script will stop working as soon as nvm switches to a different node version.

Here's how I solved it:

. /root/.nvm/nvm.sh
NODE_VERSION=`nvm current`
PATH=/usr/bin:/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/root/.nvm/versions/node/$NODE_VERSION/bin
NODE=$(which node)

First, we source (the . command) the nvm environment, which makes the nvm command available.

Then we use the nvm to tell us the currently selected node version.

Then we add the folder where that version lives to $PATH

Lastly, we call which node as usual.

#node-js #debian