How to install Node.js using NVM on Ubuntu

Introduction

I recently went through the rigmarole of trying to install a relevant version of Node.js on my Digital Ocean droplet, which is built from an Ubuntu 14.04 x64 image. At first I thought I’d just install it using Ubuntu’s package manager but it quickly became apparent that the version contained there is rather old (0.10, the latest as of writing this is 4.2).

So after some research I found that the best way to go about doing this is to use a script called NVM (Node Version Manager). As the name implies, NVM allows you to install and manage multiple versions of Node.js. An added benefit of NVM is that it installs Node.js at the user-level. This means I don’t need to worry about all my applications sharing one global version of Node.js. It helps to keep Node.js applications isolated in the manner that virtualenv does for Python.

Prerequisites

Before we install NVM we’ll need to install a couple required packages:

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

Installing NVM

Now make sure you’re logged in as the user you want to run Node.js with and install the script with this command.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash

After that you need to logout and login in for your shell to pickup the changes or you can remain logged in and run this.

source ~/.profile

NVM Usage

Now that NVM is installed I’ll run through the basics. For more information on other options see the documentation here.

Installing and running versions

To install and use the latest stable version:

nvm install stable
nvm use stable

To install and use a specific version:

nvm install 4.2
nvm use 4.2

Running the node command will execute whatever version you’ve set with use.

nvm use 4.2
node -v

To execute a specific version with calling use:

nvm run 4.2 -v

Setting a default version

To set the version that will be used as the default whenever you login to a shell:

nvm alias default 4.2

Listing installed and available versions

To see a list of which versions you have installed:

nvm ls

To see a list of which versions you can install:

nvm ls-remote