loading...

Use the correct version of Node when starting VS Code terminal session using Fish

babak profile image Babak ・2 min read

I like using Fish for interactivity at the terminal

https://fishshell.com

I also like using VS Code.

There are times I am working in a project that requires a specific version of Node. The problem I was having was that each and every time I opened up a new terminal in VS Code, I would have to remember to switch to the correct node version. Sure I could have an .nvmrc file, but then I would have to remember to issue nvm use. I could have my login script automatically issue that command; however, .nvmrc might be located in the parent directory.

Here is what I wanted:

  • Upon login check to see if there is a .nvmrc in the parent directory
  • If so, load the settings there
  • If not, do nothing

I discovered most of what I was after in this post by btoueg on GitHub

https://github.com/nvm-sh/nvm/issues/110#issuecomment-442955314

From that post I derived what I was looking for. First we need a find-up by btoueg and another function that will issue the nvm use command per .nvmrc found in our path.

function find-up --description 'Find file recursively in parent directory'

    set path (pwd)

    while test "$path" != "/" ; and not test -f "$path/$argv[1]"
        set path (dirname $path)
    end

    if test -f "$path/$argv[1]"
        echo "$path/$argv[1]"
    else
        echo ""
    end

end


function nvm-use --description 'run nvm using .nvmrc in parent directory'

  set loaded_version (node --version)
  set nvmrc (find-up '.nvmrc')

  if test -f $nvmrc
    set nvmrc_version (cat $nvmrc)
    if test $loaded_version != $nvmrc_version
      nvm use --silent
    end
  end

end

Then simply invoke it

nvm-use

I have that setup in my fish config file ~/.config/fish/config.fish. Now every time I open a new terminal in VS Code, it automatically switches to the correct version of node by looking for (and finding) .nvmrc in a parent directory.

Posted on by:

babak profile

Babak

@babak

Twitter @babakness https://twitter.com/babakness

Discussion

pic
Editor guide