Do you use Node Version Manager? Try This

Geoff Dutton
Fake Weblog
Published in
2 min readAug 24, 2017

--

NVM is awesome, especially at the rate new versions of Node are coming out. If you don’t have it, you should get it. It allows you to instantly switch between any version of Node.

Hoarding ALL the Node versions!

If you didn’t already know, you can include a .nvmrc file in a project directory with the contents of the intended Node version, so like:

# .nvmrc (Note: NVM doesn't recognize comments, so remove this line)
8

Or if you need a more specific version:

# .nvmrc (Note: NVM doesn't recognize comments, so remove this line)
v7.10.1

Now if I’m in ~/Projects/my-cool-thing, I can just run nvm use and it will switch to whatever version is in the .nvmrc file.

However, that seems absolutely absurd to have to run a command when you enter a project directory. Here’s what I did.

First, I added this to my ~/.profile file:

# ... a bunch of other unorganized shit ...
[ -f "$(pwd)/.nvmrc" ] && nvm use

That’s a start. When I open a terminal to the project directory, it’ll run the command to switch to the project version of Node, but let’s get lazier by hooking in to the cd command. Here’s what I added next:

# ... a bunch of other unorganized shit ...
[ -f "$(pwd)/.nvmrc" ] && nvm use
cd() {
builtin cd "$1"
[ -f "$(pwd)/.nvmrc" ] && nvm use
}

Now back to writing code that’s not bash!

--

--