Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active November 19, 2023 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hungdev/14875a10b136aacb090a67ceec433c3a to your computer and use it in GitHub Desktop.
Save hungdev/14875a10b136aacb090a67ceec433c3a to your computer and use it in GitHub Desktop.
Node switcher version shellscript command

Node switcher:

How to use:

Create file name: node-swicher.sh and copy content below
give permission ( Only need to grant 1 time ): chmod +x node-swicher.sh
run it: ./node-swicher.sh $param
param: 
If no number is passed, it defaults to version 16.16.0.
If 14 is passed, it uses version 14.19.0.
If 16 is passed, it uses version 16.16.0.
If another number is passed, it attempts to find the last valid Node.js version based on that number. If not found, it defaults to version 16.16.0.

Example: 
./node-swicher.sh 14
./node-swicher.sh 15
./node-swicher.sh 16
./node-swicher.sh 17
./node-swicher.sh 17.8.0
./node-swicher.sh
...

Here is node-swicher.sh content:

#!/bin/bash

if [ $# -eq 0 ]
then
    version_string="16.16.0" # Default version is 16.16.0
else
    version=$1
    
    # Handling specific cases for numbers 14 and 16
    if [ $version -eq 14 ]
    then
        version_string="14.19.0"
    elif [ $version -eq 16 ]
    then
        version_string="16.16.0"
    else
        # Finding the last valid version based on the provided number
        version_string=$(fnm list-remote | grep "^v${version}" | tail -n 1 | sed "s/^v//")

        # If no valid version is found, choose the default version
        if [ -z "$version_string" ]
        then
            echo "No valid version found for number $version. Using the default version."
            version_string="16.16.0"
        fi
    fi
fi

# Executing the commands with the version string
fnm install $version_string
fnm use $version_string
fnm default $version_string

echo "Selected version $version_string"
@hungdev
Copy link
Author

hungdev commented Nov 19, 2023

#!/bin/bash

version=$1

if [ "$version" = "14" ]; then
  version_string="14.19.0"
elif [ "$version" = "16" ]; then  
  version_string="16.16.0"
else
  version_string=$(fnm ls | grep "^$version" | tail -1)
  if [ -z "$version_string" ]; then
    version_string="16.16.0"
  fi  
fi

fnm install $version_string
fnm use $version_string
fnm default $version_string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment