Sitemap
The Tech Collective

Welcome to our publication, where technology and engineering culture take center stage. Delve into the fascinating world of tech, exploring its advancements, challenges, and impact on society. Share your insights and experience!

Taming Node — Part 2: Advanced NVM usage and workflows

6 min readAug 12, 2024

--

This is the second in a series of articles where we will help tame Node.js by automating some of the NVM processes. As a result, this will help increase our development productivity and reduce some of the frustrations caused by the Node.js ecosystem.

Develops workstation showing images with nvm and taming node part 2
Image generated with DALL-E

Introduction

In the previous article Taming node — Part 1: Managing node.js versions effectively with NVM, we discussed installing NVM and how to install and switch Node.js versions. In this article, we will take things a step further by using .nvmrc files to automate the process of version switching.

Nic Cage showing that it’s go time
https://giphy.com/gifs

How to Set a Default Node.js Version:

A common issue, often faced by JS developers is the inconsistency in Node.js versions across projects. It’s not uncommon to try running a project only to be greeted with a terminal full of errors because it was built with a different version of Node.js. This can be especially confusing and frustrating for those new to Node.js.

Setting a default version is the first step to gaining consistency. To do this, we first need to make sure the version we want to set as default is already installed:

nvm ls # This will list the currently installed versions

If the correct version is already installed we can skip the next step:

Note: Feel free to switch out 18.17.0 for a version of Node.js you find most useful to have as default.

nvm install 18.17.0

Once we have the version installed then we can set the default:

nvm alias default 18.17.0

With the default set, Every time we open a new terminal, NVM will automatically use that version of Node.js unless we manually switch to a different version.

Using LTS versions as default

Why use LTS? As discussed in the previous article I’ll let ChatGPT explain as it does it better than I can:

“Using LTS (Long Term Support) versions of Node.js is important because these versions are maintained with security updates and critical bug fixes for an extended period, ensuring greater stability and reliability for production applications.”

So we now know using LTS versions is a good thing. We have it installed, now let’s see how we can make it the default.

nvm alias default lts/*

Some eagle-eyed readers may have noticed the * in the above command. This is a convenient way to automatically use the latest LTS version of Node.js as your default. It simplifies version management, ensures that you’re always on a stable release, and reduces the need for manual updates when new LTS versions are released.

NOTE: Node.js LTS versions are named after elements from the periodic table, with each LTS release line receiving a unique name, such as “Argon,” “Boron,” “Carbon,” and so on, to differentiate between them and provide an easy reference to their specific LTS cycle.

You can see more information on what releases are available by visiting: https://nodejs.org/en/about/previous-releases#looking-for-latest-release-of-a-version-branch

Creating and Using .nvmrc Files

When working on multiple projects sometimes a different version of Node.js is required for each project. To address this, we can create a .nvmrc file in the root folder of the project. You can do this with your favourite IDE, text editor or with:

echo "20.15.1" > .nvmrc

You can put the exact Node.js version number (e.g. 18.17.1) or use aliases like lts/* in the .nvmrc file. It can also start with a v (e.g. v20.15.1) but it’s not necessary

Once the .nvmrc file is in place, we can configure NVM to automatically switch to the version specified in the file when navigating to the project directory.

Manually switching to the version specified in the .nvmrc file can be done by running:

nvm use

To automatically switch Node.js versions when entering a project directory, the following function is added to the shell profile (e.g., ~/.bashrc or ~/.zshrc):

cd() {
builtin cd "$@"
if [ -f .nvmrc ]; then
nvm use
fi
}
Man showing the benefits are huge
https://giphy.com/gifs

Advanced Node.js Version Switching in Zsh

For developers using the Zsh shell, you can further automate the process of switching Node.js versions by using a custom script. This script automatically loads the correct Node.js version when navigating between directories, based on the .nvmrc file in the project.

Add the following script to the Zsh configuration file (e.g., ~/.zshrc):

autoload -U add-zsh-hook
load-nvmrc() {
local node_version="$(nvm version)"
local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$node_version" ]; then
nvm use
fi
elif [ "$node_version" != "$(nvm version default)" ]; then
echo "Reverting to nvm default version"
nvm use default
fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

Once we have edited the script, a reload is required for the Zsh configuration to apply the changes. We can do that by running this command:

source ~/.zshrc

Once this has run, the .nvmrc file will dictate which version to switch to.

Creating a PowerShell Function to Use .nvmrc

If using a Windows machine, PowerShell can also be configured to switch nvm versions. We do this by adding the .nvmrc file and adding some custom functions.

First, open the PowerShell profile script for editing. You can find your profile script by using the following command:

notepad $PROFILE

Add the following function to the profile script:

function Use-Nvmrc {
$nvmrcPath = Join-Path (Get-Location) ".nvmrc"

if (Test-Path $nvmrcPath) {
$nodeVersion = Get-Content $nvmrcPath
$currentNodeVersion = nvm version

if ($currentNodeVersion -ne $nodeVersion) {
Write-Host "Switching to Node.js version $nodeVersion"
nvm use $nodeVersion
} else {
Write-Host "Already using Node.js version $nodeVersion"
}
} else {
Write-Host "No .nvmrc file found in the current directory."
}
}

After saving the changes, reload the PowerShell profile to make the function available in the current session:

Use-Nvmrc

If we want to make this process automatic whenever we change directories, we can override the cd command by adding the following command to our profile:

function Set-Location {
param([string]$path)
Microsoft.PowerShell.Management\Set-Location $path
Use-Nvmrc
}
Man rubbing hands showing it’s all done
https://giphy.com/gifs

Conclusion

In this second instalment of the “Taming Node” series, we’ve delved into advanced NVM usage, focusing on how to set default Node.js versions and leverage .nvmrc files for project-specific version management. We also explored automating the switching process with Zsh and Powershell. Hopefully, this will make working with multiple versions of Node.js across different projects much less painful.

Stay tuned for the next article in this series, where we will dive into managing dependencies with Node and npm, further enhancing your productivity and control over your Node.js projects.

Waving until next time
https://giphy.com/gifs

References

This article was helpfully checked and corrected into something resembling non-Northern English by Grammarly and ChatGPT

--

--

The Tech Collective
The Tech Collective

Published in The Tech Collective

Welcome to our publication, where technology and engineering culture take center stage. Delve into the fascinating world of tech, exploring its advancements, challenges, and impact on society. Share your insights and experience!

Andrew Allison
Andrew Allison

Written by Andrew Allison

17-plus years of professionally putting characters in places that produce great software systems. A lifetime of hacking on computers.

No responses yet