BASH

Automate NVM Setup and Node Version Switching

Streamline your Node.js development workflow by automating NVM (Node Version Manager) initialization and switching between Node versions in Bash scripts.

#!/bin/bash

# Load NVM (Node Version Manager) if installed
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion

# Check if NVM is loaded
if ! command -v nvm &> /dev/null; then
  echo "Error: NVM is not installed or not loaded. Please install NVM first."
  exit 1
fi

TARGET_NODE_VERSION="18.17.0" # Example version

# Install the target Node version if not already present
nvm install "$TARGET_NODE_VERSION" || { echo "Failed to install Node $TARGET_NODE_VERSION."; exit 1; }

# Use the target Node version
nvm use "$TARGET_NODE_VERSION" || { echo "Failed to use Node $TARGET_NODE_VERSION."; exit 1; }

echo "Successfully set Node.js to version $(node -v) and npm to version $(npm -v)"

# Example: Run a Node.js command
# node -v
# npm install
# npm run build
How it works: This script automates the process of setting up and switching Node.js versions using NVM (Node Version Manager). It first sources the NVM scripts to load NVM functions into the current shell. It then checks if NVM is properly loaded. Finally, it attempts to install a specified `TARGET_NODE_VERSION` if not already present and then switches to use that version, making it ready for any subsequent Node.js or npm commands within the script.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs