Upgrading Node.js on Ubuntu can be done via the NodeSource repository or by using a version manager such as nvm (Node Version Manager). I’ll walk you through both methods.
Method 1: Using NodeSource Repository
-
Update the package index:
sudo apt update
-
Install curl if you don’t have it installed already:
sudo apt install curl
-
Add the NodeSource APT repository for the version of Node.js you want (in this case, Node.js 16, but you can change the version number as needed):
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
-
Install Node.js:
sudo apt-get install -y nodejs
-
Verify the installation:
node -v npm -v
This should install and upgrade your Node.js to the specified version.
Method 2: Using nvm (Node Version Manager)
-
Download and install nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
-
Reload your shell configuration (you might need to close and re-open your terminal, or run the following command):
source ~/.bashrc
-
Verify nvm installation:
command -v nvm
-
Install the desired version of Node.js using nvm (for instance, the latest version):
nvm install node
Or you can install a specific version:
nvm install 16.13.0
-
Set the default Node.js version (optional):
nvm alias default 16.13.0
-
Verify the installation:
node -v npm -v
Using nvm
is particularly useful if you need to manage multiple versions of Node.js on the same system.
Choose the method that best fits your needs. If you’re looking for simplicity and only need a single version of Node.js, the NodeSource repository method will suffice. If you need flexibility to switch between different versions, nvm
is the way to go.