How to install the latest versions of NodeJS and NPM?

Fresh installation

Use the NodeSource PPA. For details look at the installation instructions. First, choose the Node.js version you need and add the sources for it:

v=8   # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

P.S.: curl package must be installed on server for these code lines.

Upgrading

If you have nodejs already installed and want to update, then first remove current instalation and install it again using scripts above.

sudo apt-get purge nodejs npm

Generally speaking, loading arbitrary data from a URL into a root shell session is not a good idea and I wish people would stop peddling it as a solution for everything - "Please just run this script I'm sending you, and also while we're at it - I have a bridge you'd probably be interested in purchasing".

As an alternative, here's the "Ubuntu Way" of doing the same, where you can see how the system is being updated and know what repositories and what keys are added to your system configuration:

curl https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
sudo apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install nodejs

This is for the latest (at time of writing) Nodejs version 7. Other versions can also be gotten with a simple change to the repo URL - consult nodesource.com documentation for details.


Node.js v4.x:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs

source: https://github.com/nodesource/distributions#debinstall