Managing your Node.js versions

Managing your Node.js versions

At times when you’re working on multiple projects and each of them have a dependency of a different version of Node.js, this can be very frustrating. This is where the Node Version Manager (nvm) steps in. What the nvm does it allows you to install multiple versions of Node.js on the same machine which can easily switch over and make it per project basis.

To install nvm you may need the build tools relevant to your OS, individual instructions can be found from the github readme. Once you have all the prerequisites, simply issue the following command in your favorite terminal.

Bash
1
2
3
curl -o- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
# or Wget
wget -qO- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash

The script may automatically inject some lines into your (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc) depending on your platform.

If it does not, simply paste in the following to one of the files mentioned above.

Bash
1
2
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

Well now you are ready to use nvm, may need to restart your terminal for it to kick in. To install a specific version simply do nvm install 6.9.1 and replace it with the version you actually want. To switch to another version simply do nvm use 7.1.0

Here’s the fun part, you can also make it automatically switch to a Node.js version by folder or project basis. How this works is in your project add a new file called .nvmrc and in it put the version you want. e.g.

Bash
1
echo 6.9.1 > .nvmrc

You may also want to put the following in your user shell file.

Bash
1
echo '[ -s ".nvmrc" ] && nvm install' >> ~/.bash_profile

What this does is that if it finds the .nvmrc file in the current directory, it will execute nvm install automatically which will switch to the specified version in the config file. If the version has not yet been installed, you can run nvm install without specifying the version as it is already in the .nvmrc file.

Depending on your IDE or terminal this can work very well if it supplies the cwd automatically. I’m using WebStorm and Intellij, it seems to work quite well. Now when I open any Node.js project of mine, it will switch to the right version automatically! Happy life.

I hope that you guys enjoyed reading this article as much as I liked writing it. As always for any questions please post it in the comments below, I will be more than happy to assist.