morganestes
3/26/2015 - 3:01 AM

Shell script to update node.js to latest version (OS X).

Shell script to update node.js to latest version (OS X).

# Update to the most recent version of Node.js (and npm).
# Pass -f to force an update.
node-update() {
	local force=false
	local current=`node -v`
	local latest=`curl -s https://nodejs.org/dist/latest/ | egrep -o 'node\-v([0-9\.]+)\.pkg' | head -n1`

	while getopts ":f" opt; do
		case "$opt" in
			f) force=true ;;
		esac
	done

	echo "Current package: node-${current}.pkg"
	echo "Latest package: $latest"

	if [[ "node-${current}.pkg" != $latest || $force == true ]]
		then
			mkdir -p "$HOME/tmp"
			cd "$HOME/tmp"
			echo "Updating node.js to ${latest}."
			# Check to see if current package already exists locally.
			if [ ! -f "$HOME/tmp/node-${current}.pkg" ]
				then
				wget https://nodejs.org/dist/latest/$latest
			fi
			sudo installer -pkg $latest -target /
			echo "Node is now at ${current}; npm is `npm -v`."
			cd -
		else
			echo "You're already running the latest version of node.js (${current})."
	fi
}