Month: June 2016

How to switch to your project’s version of node when you cd into it.

If you’re using nvm to manage multiple versions of node.js, then you’ll want to automatically switch to the appropriate version of node for that project when you switch (cd) into it’s directory. The simplest, easiest, and most elegant way I’ve found so far is by adding the following lines into your .bash_profile or .bashrc:


# Method to check for existence of .nvmrc
# and switch versions if needed.
load-nvmrc() {
if [[ -f .nvmrc && -r .nvmrc ]]; then
nvm use
fi
}

# Override the cd command to load nvmrc
# whenever someone uses cd to switch into
# a directory
function cd () {
builtin cd "$@" && load-nvmrc;
}

Essentially we’re overriding the cd command to do some extra lifting. After adding the above code, you’ll want to reload / restart your terminal. Also, you’ll want to add an .nvmrc file to each project that uses a specific version of node. In the .nvmrc file, simply specify the version of node you’d like nvm to load when you cd into that project.

One of my project’s .nvmrc files looks like this:

4.4.5