A dotfile that will set the default node version on a project using nvm?

There is now some native support for this built into direnv's stdlib. It's documented in their wiki, but the source is just as easy to read, or type direnv stdlib to find it).

$ node -v
v8.0.0
$ cat .node-version
4.3.2
$ cat .envrc
use node
$ export NODE_VERSIONS=~/.nvm/versions/node
$ export NODE_VERSION_PREFIX=v
$ direnv allow
direnv: loading ~/.config/direnv/direnvrc
direnv: loading .envrc
direnv: using node
direnv: Successfully loaded NodeJS v4.3.2 (via .node-version), from prefix (~/.nvm/versions/node/v4.3.2)
direnv: export +CPATH +LD_LIBRARY_PATH +LIBRARY_PATH +PKG_CONFIG_PATH ~MANPATH ~PATH
$ node -v
v4.3.2
$ direnv deny
direnv: error .envrc is blocked. Run `direnv allow` to approve its content.
$ node -v
v8.0.0

If you want node_modules/.bin in your path, just add the line layout node to your .envrc (the source is also in direnv stdlib output).


You can do this with a combination of NVM, dotfiles in your project directory, and a little tool called direnv which allows you to load in environment variables on a per-directory basis.

http://direnv.net/

Install NVM and direnv, and then cd to the directory you want to change Node versions in.

Add a file called .nvmrc in that directory, containing just the version number of the Node version you want to auto-switch to, e.g.,:

6.2.2

Then add an environment configuration file called .envrc to your directory, containing this script:

nvmrc=~/.nvm/nvm.sh
if [ -e $nvmrc ]; then
  source $nvmrc
  nvm use
fi

PATH_add node_modules/.bin

If you now cd out of this directory, and then cd back in, direnv will kick in and you should be asked to add the directory to your direnv whitelist by typing direnv allow . at the prompt. Once whitelisted, direnv will auto-run that script whenever you enter this directory, setting your Node version to the version number in .nvmrc.

As a bonus, it will also add the node_modules directory to your PATH, so you can execute binaries from those directories without prepending the node_modules path.