How to install NodeJS using NVM on Ubuntu

NodeJS is a platform that runs JavaScript on the server, allowing developers to build fast network applications quickly. In this tutorial I will show you how to install NodeJS on your Ubuntu machine using NVM.

You may be wondering right now, why do we need to use NVM while we can install NodeJS from Ubuntu repositories using apt-get?

1
2
3
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm

Well, yes that’s true, you can install NodeJS easilly like this, but though it’s correct it has some drawbacks! The first one, which had always annoyed me a lot, you’ll always have to use sudo when working with NodeJS (Executing programs, installing packages…). Second one is you’re stuck with the version available on Ubuntu repositories, you’ll never get the latest version, and you’ll have a hard time trying to switch to older versions as well.

NVM solves these problems by allowing you to install multiple, self-contained versions of NodeJS. Thus, you’ll have total freedom choosing the version you want to use, and of course, you will never have to use sudo again!

First thing to do is the make sure we have build-essential and libssl-dev installed, NVM requires those two packages installed to build NodeJS.

1
2
sudo apt-get update
sudo apt-get install build-essential libssl-dev

Now to install NVM, you simply need to execute the following command:

1
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.26.0/install.sh | bash
nvm-install-command.png

Now just close your current terminal and open a new one, and you will be able to use NVM.

nvm-help.png

Typing NVM alone will display a help document that explains how to use it. Let’s say we wan to list all available NodeJS versions:

1
nvm ls-remote
nvm-ls-remote.png

If you want to know just the latest stable version instead:

1
nvm ls-remote stable

Okay, now that we know what the latest version is, let’s go ahead and install it!

1
nvm install v0.12.7

Or:

1
nvm install 0.12.7

Or simply:

1
nvm install stable
node-installed.png

Want to install another version? Just do the same thing again and again and again… Now that you have multiple NodeJS versions installed on your machine, let’s say you want to switch from 0.12.7 to 0.12.5:

1
nvm use 0.12.5
nvm-use.png

Too easy, huh? However, NVM will forget the NodeJS version you were using right when you close your terminal, and the next time you try to use NodeJS, you will be shown a cute shiny error telling you “command not found: node”. That’s because we didn’t tell NVM which version to use by default. This can be easily done using aliases:

1
nvm alias default 0.12.7
nvm-alias.png

That’s it, you now have NodeJS installed with the default version set to 0.12.7, next time you open your terminal NVM will automatically load this version for you.