Using `.zshrc` file and Homebrew as a Node.js Version Manager and alternative to nvm

Overview

Instead of using nvm (Node Version Manager), you can manage multiple Node.js versions using Homebrew and your

.zshrc

file. This approach involves installing different Node.js versions via Homebrew and updating your PATH environment variable to switch between versions.

Steps to Set Up

  1. Install Node.js Versions via Homebrew:

     brew install node@16 node@18 node@20 node@22
    
  2. Add the following line to your .zshrc file

# Node.js version (Change version number after "node@xx" to change your node version)
export PATH="/opt/homebrew/opt/node@20/bin:$PATH"
  1. Switch Node.js Versions: To switch Node.js versions, change the version number in the export PATH line in your .zshrc file. For example, to switch to Node.js 18:
export PATH="/opt/homebrew/opt/node@18/bin:$PATH"
  1. Apply Changes: Source your .zshrc file to apply the changes OR simply open a new terminal window.
source ~/.zshrc

Pros and Cons

Using Homebrew and .zshrc:

Pros:

  • Simplicity: Straightforward setup and usage.

  • Integration: Works seamlessly with Homebrew, which is commonly used on macOS.

  • No Additional Tools: No need to install and manage an additional tool like nvm.

  • Avoids the needs for nvm, which can have compatibility and installation issues on some machines.

Cons:

  • Manual Updates: Requires manual editing of the .zshrc, instead of typing a terminal command.

  • Limited Flexibility: Less flexible compared to nvm for quickly switching between versions or using different versions in different terminal sessions.

Using nvm:

Pros:

  • Ease of Use: Simple commands to switch between Node.js versions (nvm use <version>).

  • Flexibility: Allows different terminal sessions to use different Node.js versions.

  • Project-Specific Versions: Supports .nvmrc files for project-specific Node.js versions.

Cons:

  • There can be compatibility and installation issues on some machines.

  • Additional Tool: Requires installing and managing nvm.

  • Overhead: Slightly more overhead in terms of setup and learning curve.

Conclusion

Using Homebrew and .zshrc to manage Node.js versions is a simple and effective approach if you prefer minimal tooling and are comfortable with manual configuration. However, if you need more flexibility and ease of switching between versions, nvm might be a better choice.

0
Subscribe to my newsletter

Read articles from Brandon C Roberts directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Brandon C Roberts
Brandon C Roberts