Last active
December 10, 2020 01:38
-
-
Save bschlenk/608d8fafff8c7cf2a3bdf4bffdd5b63f to your computer and use it in GitHub Desktop.
Update Node, reinstall global packages, and remove older versions. To be placed in shell profile.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Automate installing a new version of node, re-installing global | |
# node modules, and uninstalling older node versions. | |
# | |
# Depends on nvm, semver, and python3. | |
# | |
# semver will be auto-installed if it doesn't exist yet. | |
# | |
# If a single arg is given: | |
# | |
# 1. Install the new node version given as the first arg. | |
# 2. Switch to the new node version. | |
# 3. Re-install global npm modules with the new node. | |
# | |
# In all cases, node versions where there is a newer one with | |
# the same major version already installed will be removed. | |
# | |
# For example, if the following node versions are installed: | |
# | |
# 8.17.0 | |
# 10.5.0 | |
# 10.8.0 | |
# 10.18.1 | |
# 12.13.0 | |
# 12.14.1 | |
# | |
# Then 10.5.0, 10.8.0, and 12.13.0 will all be uninstalled. | |
# The rest will be left alone. | |
nvm-clean-install() { | |
if [ "$#" -eq 1 ]; then | |
nvm install "$1" --reinstall-packages-from=$(node --version) --latest-npm | |
fi | |
if ! command -v semver > /dev/null 2>&1; then | |
npm i -g semver | |
fi | |
local NODE_DIR=$NVM_DIR/versions/node | |
local REMOVE_VERSIONS=$(semver $(ls $NODE_DIR) | tail -r | python3 -c 'import sys; vers = map(lambda x: x.strip(), sys.stdin.readlines()); seen = set(); vers = filter(lambda x: x.split(".")[0] in seen or seen.add(x.split(".")[0]), vers); print("\n".join(vers))') | |
if [ ${#REMOVE_VERSIONS[@]} -ne 0 ]; then | |
echo "uninstalling old node versions..." | |
for v in $REMOVE_VERSIONS; do | |
nvm uninstall $v | |
done | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment