Node Version Management... Automatically
Stephen Charles Weiss
Posted on February 26, 2020
NVM, the Node Version Manager, is an invaluable tool when working on multiple node projects. Instead of manually managing the globally installed version of node, NVM can handle it for you.
Unfortunately, even with NVM, it’s easy to use the wrong node version when jumping between projects.
A colleague shared his solution to the problem with me recently:
//".bash\_profile"
function cd() {
builtin cd "$@"
nvm i 2> /dev/null
}
This function, when added to the .bash_profile
(or .zshrc
, etc.), will still perform the change directory as expected (that’s the first line: builtin cd "$@"
), but it will also look for the presence of an .nvmrc
file in the new directory.
Quick Aside: What Is The .NVMRC?
It’s worth taking a moment to discuss the .nvmrc
file, it’s function, and what it may look like:
You can create a .nvmrc file containing a node version number (or any other string that nvm understands; see nvm —help for details) in the project root directory (or any parent directory). Afterwards, nvm use, nvm install, nvm exec, nvm run, and nvm which will use the version specified in the .nvmrc file if no version is supplied on the command line.
So, for example, you could have an .nvmrc
for a specific version:
//.nvmrc
12
Or you could default to the latest LTS version:
//.nvmrc
lts/*
If there’s an .nvmrc
included in the new directory, the function will execute /dev/null
.
An example of this in use. The directory, personal , does not have an .nvmrc file, though onething does. Upon detecting it, nvm automatically switched to using the correct node version. |
As noted in the description of the .nvmrc
, it’s presence ensures that nvm i
will use the version specified in the file.
The /dev/null
is a specific form of redirection within Unix.
In this case it’s saying take the stderr
(2
), redirect (>
) to /dev/null
. The /dev/null
is a “blackhole” on unix machines, effectively suppressing any errors generated by running this command.
Final Note
NVM manages node versions within each terminal session. This is critical because it ensures that you can run two node projects simultaneously even if the node versions are different.
Posted on February 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.