Almost a year ago I posted an article about how to run npm without sudo that seems to have helped a few people.
Actually, I have long since switched to using nvm (as suggested in one of the comments) which I find to be a much better solution. Since someone recently posted a comment saying that my old solution was causing issues, I wanted to make a follow-up post.
Node Version Manager
nvm describes itself as a “Simple bash script to manage multiple active node.js versions”, a job which it does very well in my opinion.
You can install it using the provided install script via cURL or Wget if you’re running bash (check here for the latest version):
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash
If you’re on Mac, you might prefer to use the excellent Homebrew package manager (I do!):
brew install nvm
Once nvm is up and running, you can pick a version of Node to install. The latest version as I write this is v4.2.1. To list all the available versions, you can use the
nvm ls-remote # v0.1.14 # v0.1.15 # ... # v4.2.0 # v4.2.1
Once you know which version of Node you want, install it like this:
nvm install v4.2.1
nvm will have automatically activated the newly installed version of Node ready for you to use:
node -v # v4.2.1 npm -v # 2.14.7
To get nvm to keep your newly installed version always available, just set it as the default version like this:
nvm alias default 4.2.1
If all you wanted to do was painlessly install Node and npm without any of the sudo pain my previous post set out to solve, then you’re done, but there’s more that nvm can do!
Let’s say you want to install a previous version of Node and npm so you can run an old project with npm dependencies that are incompatible with the latest version… you don’t need to uninstall and downgrade, you can just add another version using nvm:
nvm install v0.12.4
You can list your installed versions like this:
nvm ls # -> v0.12.4 # v4.2.1 # default -> 0.12.4 (-> v0.12.4) # node -> stable (-> v4.2.1) (default) # stable -> 4.2 (-> v4.2.1) (default) # iojs -> iojs- (-> N/A) (default)
And switch between them like this:
node -v # v0.12.4 nvm use 4.2.1 node -v # v4.2.1