Automatically Switch Node Versions Based on Your Package.json and Precmd in ZSH

I enjoy using the very latest version of node.js for my quick scripts I write on my computer. That means that my nvm is set to run Node v14. Every time I’ve fired up our egghead-next project recently, I’ve had to switch to Node.js v12 (the latest stable version) to run yarn dev. I was getting sick of running nvm use 12 every time I opened a shell, so I set out to see what I could do.

It turns out that zsh has a precmd “hook” that allows you to run some code each time you open a new prompt. That gave me an idea to check my current Node version against the Node version listed in the package.json.

The hook is a function living inside of my .zshrc file.

You will need to install jq for this function since I use it to read the “engines” field on the package.json.

The script reads like this:

  1. If a package.json exists
  2. set the nodeVersion to the .engines.node field
  3. if nodeVersion exists and nvm isn’t set to that version
  4. nvm use the first two characters of nodeVersion
if [ -f package.json ]
nodeVersion=$(jq -r '.engines.node | select(.!=null)' package.json )
if [ ! -z $nodeVersion ] \
&& [[ ! $(nvm current) = "^v$nodeVersion" ]]
echo "found $nodeVersion in package.json engine"
nvm use ${nodeVersion:0:2}

Now this just runs in the background each time a new prompt fires up and I never have to think about it again! 🎉

Of note, JRGould also shared his script with me where he’s checking against .nvmrc files. Definitely worth considering this approach too!

Get Automation Tips in Your Inbox

Sign-up to get Automation tips sent directly to your inbox to improve your daily computer life!

    No spam. Unsubscribe whenever.