If you’ve ever tried to set up your pipeline with Node.js and found yourself struggling to get it to recognize the correct version of your project, then this article is for you!
To kick things off, why we even need NVM (Node Version Manager) in the first place. Well, if you’re like me, you have multiple projects that require different versions of Node.js. Maybe one uses v10 and another needs v12 it can be a real pain to keep track of all those installations!
That’s where NVM comes in handy. It allows us to easily switch between different versions of Node.js without having to mess around with global installations or environment variables. And the best part? It works on pretty much any platform, including Windows, macOS, and Linux!
So how do we get it set up in our CI/CD system? Well, there are a few different ways depending on which tool you’re using. For example, if you’re using Jenkins, you can add the following script to your pipeline:
#!/bin/bash
set -e # This sets the script to exit immediately if any command fails
# Install NVM and Node.js v12
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash # This downloads and runs the NVM installation script
export NVM_DIR="$HOME/.nvm" # This sets the NVM directory to the user's home directory
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads the nvm script
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads the nvm bash completion script
nvm install v12 # This installs Node.js v12 using nvm
This script will download and run the NVM installation script, set up some environment variables for NVM, and then install Node.js version 12. Pretty simple!
Of course, this is just one example your setup may vary depending on which CI/CD tool you’re using or what specific versions of Node.js you need to use. But the basic idea is always the same: download NVM, set up some environment variables, and then install the desired version(s) of Node.js!
Just remember to keep your scripts simple and straightforward, and always test them thoroughly before pushing them to production.