Install any supported  Node.js version, with CLI or script in the ubuntu 22.04 server

Install any supported Node.js version, with CLI or script in the ubuntu 22.04 server

First way


curl -sL https://deb.nodesource.com/setup_16.x -o /tmp/nodesource_setup.sh
sudo bash /tmp/nodesource_setup.sh

 sudo apt-get install -y nodejs

Verify

node -v

Second way

curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&\
sudo apt-get install -y nodejs

Verify

node -v

This way you can install any version of node js by just changing the version number.

Scripting way

script to install any version by just providing the node version as an integer or lts

#!/bin/bash

version=$1

if [ -z "$version" ]; then
  echo "Error: No version provided."
  exit 1
fi

if [ "$version" = "lts" ]; then
  echo "Downloading the setup script for the latest LTS version of Node.js..."
  curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
else
  if ! curl -sSf "https://deb.nodesource.com/node_${version}.x/dists/" >/dev/null; then
    echo "Error: Version $version is not supported."
    exit 1
  fi
  echo "Downloading the setup script for Node.js version $version..."
  curl -fsSL "https://deb.nodesource.com/setup_${version}.x" | sudo -E bash -
fi
echo "Updating packages"
sudo -E apt-get -qq update
echo "Installing nodejs version $version"
sudo -E apt-get -qq install -y nodejs

echo "Node.js version $version has been installed."

copy the above content in a file, and give the filename script.sh, change file permission to executable chmod +x script.sh

Usage:

will download version 14

./script.sh 14

will download version 16

./script 16

will download lts version

./script lts

Verify

Did you find this article valuable?

Support Beyond DevOps by becoming a sponsor. Any amount is appreciated!