Nodejs is included in the Ubuntu repository by default. This means that if you run:
sudo apt install nodejs
your terminal screen will be swing into action downloading the current stable release of node. Currently it is v10.19.0.
But what if you need another version? What if you need to guarantee a specific version?
First of all remove your current version of node with:
sudo apt purge nodejs
Then install curl.
sudo apt install curl
Then install the NodeSource repository
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
The command will add the NodeSource signing key to your system, create an apt sources repository file, install all necessary packages and refresh the apt cache.
If you need to install another version such as 10.x, then just replace 12.x above to 10.x. Then install node again with:
sudo apt install nodejs
and check with:
node -v
How to revert
To roll back to the default nodejs version from Ubuntu, just run:
sudo apt-get purge nodejs
and then
sudo rm -r /etc/apt/sources.list.d/nodesource.list
to delete the repository. Then if you run the standard nodejs install command, you’ll get the original default version that came with Ubuntu.