Last active
April 14, 2022 09:02
-
-
Save mrtysn/ff2a68c27b2be908c4f8188052d7d728 to your computer and use it in GitHub Desktop.
Automatically switch node version using fnm based on the required value in package.json
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
#!/usr/bin/env bash | |
# Place this script in the same directory as your package.json file. | |
# Uncomment and add the section below to your .zshrc | |
# SECTION BEGIN | |
# # nodeVersionSwitch.sh script https://gist.github.com/mrtysn/ff2a68c27b2be908c4f8188052d7d728 | |
# # fnm node version manager https://github.com/Schniz/fnm#zsh | |
# eval "$(fnm env --use-on-cd)" | |
# if [ -f "./package.json" ] && [ -f "./nodeVersionSwitch.sh" ]; then | |
# bash "./nodeVersionSwitch.sh" | |
# fi | |
# SECTION END | |
NODE_REQUIRED=$(node -p "require('./package.json').engines.node") | |
echo "Required node version in ./package.json is $NODE_REQUIRED" | |
if [[ "$NODE_REQUIRED" =~ "~"|"^" ]] ; then | |
NODE_REQUIRED="v${NODE_REQUIRED:1}" | |
N_DOT=$(grep -o "\." <<< "$NODE_REQUIRED" | wc -l) | |
if (( $N_DOT < 2 )) ; then | |
NODE_REQUIRED="$NODE_REQUIRED.0" | |
fi | |
fi | |
echo "Trying to switch to node version $NODE_REQUIRED using fnm. If this fails, you can manually switch to the required version using 'fnm use $NODE_REQUIRED'" | |
fnm use $NODE_REQUIRED | |
echo "Done. node version is now $(node -v)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment