Install NodeJS correctly with Node Version Manager

Node Version Manager is a tool that manages the installation of various NodeJS versions on the same system, and allows to easily switch between versions. Node packages can be installed as usual, but will automatically install the correct package versions for the currently active NodeJS version.

All NodeJS versions and dependent modules are installed with regular user rights and not as root user.

Remove previously installed NodeJS modules

If you have already NodeJS modules installed on your system with root user privileges, these modules should be removed first. To show all currently installed NodeJS packages, use as root user

~# npm ls -gp --depth=0

This will show all NodeJS modules installed into /usr/local. Now, remove all current NodeJS packages, and only leave Ubuntu's default system install of NodeJS (the one from the Ubuntu software repositories).

~# npm ls -gp | awk -F/ '/node_modules/ && !/node_modules.*node_modules/ {print $NF}' | xargs npm -g rm

If any NodeJS packages were previously installed under the current regular user account, they should be in ~/.npm and can remain there. Just make sure that the files were installed using the correct owner and privileges. As regular user, call the following via sudo

~$ sudo chown -R $(id -un):$(id -gn) ~/.npm
~$ sudo chmod -R 744 ~/.npm

Setup Node Version Manager

There is currently no Ubuntu package for NVM. It can be installed directly from its Github repository and will install into ~/.nvm of the current user's home directory.

~$ curl -o- | bash

There is a new directory ~/.nvm and one line was added to the user's Bash profile ~/.bashrc. If you want auto completion for Bash, you need to add another line to the Bash profile

~$ echo '[[ -r $NVM_DIR/bash_completion ]] && . $NVM_DIR/bash_completion' >> ~/.bashrc

Reload your Bash profile to activate the changes in the current shell

~$ source ~/.bashrc

Using Node Package Manager

Now use the nvm command to install different NodeJS versions, for example

~$ nvm install 5.0   # installs nodejs 0.5.0
~$ nvm install 4.2   # installs nodejs 0.4.2
~$ nvm install node  # installs latest nodejs version

and to switch between different installed versions, use

~$ nvm use 5.0    # activate node 0.5.0
~$ nvm use node   # activate latest node version
~$ nvm use system # activate Ubuntu's default node version

To install packages for a specific NodeJS version, use nvm to switch to the required version and run npm -g to install the packages as usual.

~$ nvm use 5.0
~$ npm install -g bower react-native-cli karma karma-cli karma-coverage karma-ng-html2js-preprocessor phantomjs jasmine

Both nvm and npm, should only be run as regular user.