Skip to content

Instantly share code, notes, and snippets.

@AaronPresley
Last active April 27, 2018 21:07
Show Gist options
  • Save AaronPresley/879545caf10bcbe26521b13e5791dbbf to your computer and use it in GitHub Desktop.
Save AaronPresley/879545caf10bcbe26521b13e5791dbbf to your computer and use it in GitHub Desktop.
Switch Node Script
#!/usr/bin/python
import sys
import os
NODE_VERSIONS_DIR = os.path.join(os.path.expanduser("~"), ".node-versions")
NODE_SYMLINK = '/usr/local/bin/node'
NODE_MODULE_SYMLINK = '/usr/local/lib/node_modules'
NPM_SYMLINK = '/usr/local/bin/npm'
def list_versions():
""" Lists all of the current versions of node that are available
"""
for root, dirs, files in os.walk(NODE_VERSIONS_DIR):
for d in dirs:
if d.startswith('v'):
print "- %s" % d
break
def set_version(target):
""" Sets the current version of node based on the passed target
"""
# The path to this version
target_path = os.path.join(NODE_VERSIONS_DIR, target)
# Ensure the version exists
if not os.path.isdir(target_path):
print "The directory \"%s\" wasn't found!" % target_path
exit(1)
# Generate our important paths
node_path = os.path.join(target_path, 'node')
node_module_path = os.path.join(target_path, 'out/lib/node_modules')
npm_path = os.path.join(target_path, 'deps/npm/bin/npm-cli.js')
# Bail if the node path couldn't be found
if not os.path.exists(node_path):
print "The node path \"%s\" couldn't be found" % node_path
exit(1)
# Bail if the npm path couldn't be found
if not os.path.exists(npm_path):
print "The npm path \"%s\" couldn't be found" % node_path
exit(1)
# Remove the existing node symlink if necessary
if os.path.exists(NODE_SYMLINK):
os.remove(NODE_SYMLINK)
# Create the node symlink
os.symlink(node_path, NODE_SYMLINK)
print "Updated node symlink to %s" % node_path
# Creating the node_modules symlink
if os.path.exists(NODE_MODULE_SYMLINK):
os.remove(NODE_MODULE_SYMLINK)
os.symlink(node_module_path, NODE_MODULE_SYMLINK)
print "Updated node_module symlink to %s" % node_module_path
# Remove the existing npm symlink if necessary
if os.path.exists(NPM_SYMLINK):
os.remove(NPM_SYMLINK)
# Create the npm symlink
os.symlink(npm_path, NPM_SYMLINK)
print "Updated npm symlink to %s" % npm_path
# The action passed to us from the command
action = sys.argv[1] if len(sys.argv) > 1 else None
# Show a simple help menu
if not action or action == '-h' or action == 'h':
print ("Switch Node: A simple script to allow for simple " +
"switching between node versions.\n\nUsage:")
print " switch-node <version> Switch the version"
print " switch-node ls List available versions"
print ""
print ("For info on downloading a new node version, see\n" +
"https://aaronpresley.com/multiple-node-versions-with-full-icu")
exit(0)
# Listing all versions
if action == 'ls':
print "Currently available versions:"
list_versions()
print ""
exit(0)
# Setting the version
set_version(action)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment