How to Install Node.js on an Ubuntu 22 Server

How to Install Node.js on an Ubuntu 22 Server
To install Node.js on an Ubuntu server, you have several methods to choose from. Here’s a step-by-step guide for three common methods: using the default Ubuntu repository, using the NodeSource repository, and using nvm (Node Version Manager).
Method 1: Using the Default Ubuntu Repository
- Update the package list:
sudo apt update
- Install Node.js from the default repository:
sudo apt install nodejs
- Verify the installation:
node -v
- Install npm (Node Package Manager):
sudo apt install npm
- Verify the npm installation:
npm -v
Method 2: Using the NodeSource Repository
This method is recommended for installing a specific version of Node.js.
- Update the package list:
sudo apt update
- Install the required dependencies:
sudo apt install -y curl software-properties-common
- Add the NodeSource repository:
- For Node.js 14.x:
bash curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
- For Node.js 16.x:
bash curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
- Install Node.js:
sudo apt install -y nodejs
- Verify the installation:
node -v
- npm is included with Node.js, so verify npm:
npm -v
Method 3: Using nvm (Node Version Manager)
This method allows you to manage multiple versions of Node.js.
- Update the package list:
sudo apt update
- Install the required dependencies:
sudo apt install -y curl
- Download and install nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
- Activate nvm:
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
- Verify nvm installation:
nvm --version
- Install the latest version of Node.js:
nvm install node
- Install a specific version of Node.js (e.g., 14.x):
nvm install 14
- Use a specific version of Node.js:
nvm use 14
- Set a default version of Node.js:
nvm alias default 14
- Verify the Node.js and npm installation:
bash node -v npm -v
Conclusion
These methods provide flexibility depending on your needs. The default repository method is straightforward but may not offer the latest version. The NodeSource repository is great for installing specific versions, and nvm is ideal for managing multiple versions. Choose the method that best suits your requirements.