Skip to content

Instantly share code, notes, and snippets.

@ecnepsnai
Created June 10, 2024 18:24
Show Gist options
  • Save ecnepsnai/f8d49dd03c091c319c18ed0080d6e01d to your computer and use it in GitHub Desktop.
Save ecnepsnai/f8d49dd03c091c319c18ed0080d6e01d to your computer and use it in GitHub Desktop.
Update Node
#!/bin/bash
set -e
VERSION=$(curl -Ss https://nodejs.org/download/release/index.json | jq -r '.[0].version')
INSTALL_DIR="/usr/local/node"
if [[ ! -d ${INSTALL_DIR} ]]; then
echo "Install directory '${INSTALL_DIR}' does not exist, sudo required to create it..."
sudo mkdir -p ${INSTALL_DIR}
fi
OWNED_BY=$(ls -ld ${INSTALL_DIR} | awk 'NR==1 {print $3}')
if [[ ${OWNED_BY} != $(whoami) ]]; then
echo "Install directory not writable by current user, sudo required to change that..."
sudo chown $(id -un):$(id -gn) ${INSTALL_DIR}
fi
VERSION_DIR="${INSTALL_DIR}/${VERSION}"
if [[ -d ${VERSION_DIR} ]]; then
>&2 echo "${VERSION_DIR} already exists, don't know what to do with it."
exit 1
fi
DL_URL="https://nodejs.org/dist/${VERSION}/node-${VERSION}-linux-x64.tar.xz"
cd /tmp
rm -f node-${VERSION}-linux-x64.tar.xz
curl -Ss ${DL_URL} > node-${VERSION}-linux-x64.tar.xz
tar -xf node-${VERSION}-linux-x64.tar.xz
rm node-${VERSION}-linux-x64.tar.xz
mv node-${VERSION}-linux-x64 ${VERSION_DIR}
rm -f ${INSTALL_DIR}/current
ln -s ${VERSION_DIR} ${INSTALL_DIR}/current
if [[ :$PATH: == *:"${INSTALL_DIR}/current/bin":* ]]; then
echo "nodejs updated to: $(node --version)"
else
echo "node ${VERSION} installed but is missing from your \$PATH"
echo "Add the following line to your \$PATH variable:"
echo " ${INSTALL_DIR}/current/bin"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment