• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Using jq and nvm to set Node version

Using jq and nvm to set Node version

Last updated on March 3, 2022 by Sal Ferrarello

When using nvm, one can run nvm use and if the project has a .nvmrc file in it – the version of node specified there will be set in your browser. However, on many of the projects I work on there is no .nvmrc file but the package.json file does contain an engines section and in that section it specifies the preferred version of node (just like .nvmrc would). e.g.

...
"engines": {
  "node": "12",
  "npm": "6"
},
...

While I could lookup the value in package.json and then run nvm use with that version (e.g. nvm use 12), instead I can use jq with nvm to do the lookup and set the version.

nvm use $(jq -r '.engines.node' package.json)

Shell Alias

Instead of trying to remember this command you we can setup an alias for this command. I like nvmpe for “nvm” + “p”ackage.json + “e”ngine.

e.g.

alias nvmpe='nvm use $(jq -r ".engines.node" package.json)'

Shell Function

If we want to add checks that both the nvm and jq commands are installed on the system and we have a package.json with an .engines.node entry, we could make this a shell function (we should be able to add these same checks with an alias but I’ll leave that as an exercise for the reader).

# See https://salferrarello.com/jq-nvm-set-node-version/ for explanation.
function nvmpe() {
    if ! command -v nvm &> /dev/null
    then
        echo "This command requires nvm"
        echo "See https://github.com/nvm-sh/nvm"
        return 1
    fi
    if ! command -v jq &> /dev/null
    then
        echo "This command require jq"
        echo "See https://stedolan.github.io/jq/"
        return 1
    fi

    if [[ ! -r package.json ]]
    then
        echo 'Can not read package.json in this directory'
        return 1
    fi

    node_ver=$(jq -r '.engines.node' package.json)
    if [[ $node_ver -eq '' ]]
    then
        echo "package.json does not contain an .engines.node entry"
        return 1
    fi

    # Set node version.
    nvm use $node_ver
}
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Computing, Dev Tips, Programming, Solution Tagged With: command line, jq, node, nvm

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in