tj / n

Node version management
MIT License
18.77k stars 738 forks source link

Auto switching doesn't work? #714

Closed bowencool closed 2 years ago

bowencool commented 2 years ago

Bug Report

Configuration Details

image

shadowspawn commented 2 years ago

n does not automatically change the Node.js version when you change directory. You need to run n auto, like when you run n lts.

$ cat .node-version
14.0.0
$ node --version
v14.15.4
$ n auto
       found : /Users/john/Documents/Sandpits/play/.node-version
        read : 14.0.0
  installing : node-v14.0.0
       mkdir : /usr/local/n/versions/node/14.0.0
       fetch : https://nodejs.org/dist/v14.0.0/node-v14.0.0-darwin-x64.tar.xz
   installed : v14.0.0 (with npm 6.14.4)
$ node --version
v14.0.0
jono-allen commented 2 years ago

I wrote a simple function in zsh for handling cases where there is a .nvm file.

autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(node -v | sed 's/^v\(.*\)/\1/')"
  local nvmrc_path="$(cat .nvmrc 2>/dev/null)"
  if [ -n "$nvmrc_path" ]; then
      n auto
  elif [ "$node_version" != "$(n --lts)" ]; then
    n lts_latest
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
MiniGod commented 7 months ago

I wrote something similar for bash that automatically downloads and uses the auto version, but otherwise uses the currently selected version.

# put it in .bashrc or similar
nn() {
    if n --download --quiet auto 2>/dev/null; then
        n exec --quiet auto "$@"
    else
        "$@"
    fi
}

alias npm='nn npm'
alias node='nn node'

It differs from the zsh version above in that it quietly downloads the auto version. It if fails, it just runs the command. Pros of doing it like this is that the logic of finding the auto version is determined by n, and does not error if the exact version is not installed (e.g. if the version specifies >=18, every time a new version of node is released, you would have to manually download it).

This adds a few 10s of milliseconds startup time for node and npm (if the version is already installed), but for development, I find that OK.