Automatically switching Node.js version upon cd with nvm

As I was browsing search results for that exact sentence, I stumbled upon this post which proposes a zsh script automating the switching of Node.js versions when entering a directory using nvm, based on the presence of a .nvmrc file.

It works pretty well, but where I work we already specify Node version constraints in our package.json files (under the engines key) and weren't keen on duplicating that information, since said constraints mostly consist of a strict version anyway. I therefore adapted the original script to read from there instead:

autoload -U add-zsh-hook

switch-node-version() {
if [[ -f package.json ]] && grep -q '"node"' package.json; then
nvm use `cat package.json | sed -nE 's/"node": "[^0-9]*([0-9\.]*)[^"]*"/\1/p'`
elif [[ $(nvm version) != $(nvm version default) ]]; then
nvm use default
fi
}

add-zsh-hook chpwd switch-node-version
switch-node-version

When using a range (e.g. ^11.9, >=10 <14, etc.), special characters are dropped (which would result in nvm use 10 with the latter example). This brings one caveat, which is that the script doesn't play nice with overly specific ranges, such as ^10.0.0: it would indeed try to nvm use 10.0.0, and that particular version might not be available on one's machine. In such cases, I would advise shortening the range to ^10 (which better conveys the idea anyway in my opinion).