NVM (Node Version manager) with --lts
NVM was mentioned at: https://askubuntu.com/a/441527/52975 but here goes a more complete usage example, including the sane --lts
version, which installs the latest Long Term Support version of Node, which is likely the one you want if you don't have more specific requirement.
Install NVM and the latest Node LTS version:
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.nvm/nvm.sh
nvm install --lts
nvm use --lts
npm --version
Now test it out with a dummy package:
npm install --global vaca
vaca
Since the sourcing has to be done for every new shell, the install script hacks adds some auto sourcing to the end of your .barshrc
. That works, but I prefer to remove the auto-added one and add my own:
f="$HOME/.nvm/nvm.sh"
if [ -r "$f" ]; then
. "$f" &>'/dev/null'
nvm use --lts &>'/dev/null'
fi
Advantages:
allows you to use multiple versions of Node and without sudo
is analogous to Ruby RVM and Python Virtualenv, widely considered best practice in Ruby and Python communities
downloads a pre-compiled binary where possible, and if not it downloads the source and compiles one for you
We can easily switch node versions with:
nvm install 0.9.0
nvm install 0.9.9
nvm use 0.9.0
node --version
#v0.9.0
nvm use 0.9.9
node --version
#v0.9.9
You can then use a git tracked .nvmrc
file to indicate the node version required for a given project: https://stackoverflow.com/questions/24869959/how-do-i-specify-a-local-version-of-node-for-a-project/54503474#54503474
With this setup, you get for example:
which node
gives:
/home/ciro/.nvm/versions/node/v0.9.0/bin/node
and:
which vaca
gives:
/home/ciro/.nvm/versions/node/v0.9.0/bin/vaca
and if we want to use the globally installed module:
npm link vaca
node -e 'console.log(require.resolve("vaca"))'
gives:
/home/ciro/.nvm/versions/node/v0.9.0/lib/node_modules/vaca/index.js
so we see that everything is completely contained inside the specific node version.
Tested in Ubuntu 17.10.