Skip to content

Instantly share code, notes, and snippets.

@Davydx7
Last active June 20, 2024 11:28
Show Gist options
  • Save Davydx7/d001fbd60af6e330af9f52c3b607938b to your computer and use it in GitHub Desktop.
Save Davydx7/d001fbd60af6e330af9f52c3b607938b to your computer and use it in GitHub Desktop.
Automated Node Version Switching for Windows using NVM

Automated Node Version Switching for Windows using NVM

Introduction

Managing multiple versions of Node.js can be cumbersome, especially when working on different projects that require different versions. On Unix-based systems, nvm (Node Version Manager) allows users to switch between different versions of Node.js seamlessly. However, on Windows, nvm behaves differently and does not automatically switch versions based on the .nvmrc file. This script automates the process of switching Node.js versions on Windows using nvm-windows.

Script

# Load nvm and automatically use the Node version specified in .nvmrc
load-nvmrc() {
  if [ -f .nvmrc ]; then
    local nvm_version=$(cat .nvmrc)
    local current_version=$(node.exe -v)
    if [ "$current_version" != "$nvm_version" ]; then
      nvm use "$nvm_version"
    fi
  fi
}

# Custom keybinding for Ctrl+N
bind -x '"\C-n": load-nvmrc'

# Automatically switch node versions when changing directories or at initiation
cd() {
  builtin cd "$@" && load-nvmrc
}

load-nvmrc

Script Explanation

The script provided below is intended to be placed in your .bashrc or equivalent profile file. It checks the .nvmrc file in the current directory and switches to the specified Node.js version if it differs from the currently active version. Additionally, it binds a custom keybinding for Ctrl+N to manually trigger the version switch and automatically switches versions when changing directories or initializing a terminal session.

Why This Script?

Problem Statement

  • On Windows, nvm does not automatically switch Node.js versions based on the .nvmrc file.
  • Developers often work on multiple projects requiring different versions of Node.js.
  • Manually switching Node.js versions can be error-prone and time-consuming.

Solution

  • This script automates the process of switching Node.js versions on Windows.
  • It ensures that the correct Node.js version is used based on the .nvmrc file in the current directory.
  • It provides a custom keybinding (Ctrl+N) to manually trigger the version switch.
  • It automatically switches versions when changing directories or initializing a terminal session.

Future Plans

I am considering publishing a VSCode extension to further streamline the process of managing Node.js versions on Windows. The extension will provide additional features and integrations to enhance the developer experience.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment