Node.js Linux Deployment Script

 •  Filed under installation, node.js, nodejs, linux, deployment, script

Need an easy solution to deploy the latest version of Node.js on Linux? This Bash script that I made does exactly that, and nothing more. There might be more elegant and better ways to deploy Node.js but I needed something lightweight and still as functional as solutions like nvm and n. The only things this script depends on are bash,curl,sed,grep and tar. These tools come preinstalled on almost all Linux distributions,

#!/bin/bash

# Node.js deployment script (automatically fetches the latest version)

CPUARCH="x64"  
LINK="https://nodejs.org/dist/latest/"  
DESTINATIONDIR="/opt/nodejs"

DOWNLOAD=$(curl -s $LINK | grep -o '<a .*href=.*>' | sed -e 's/<a /\<a /g' | sed -e 's/<a .*href=['"'"'"]//' -e 's/["'"'"'].*$//' -e '/^$/ d' | grep 'linux' | grep "$CPUARCH" | grep ".tar.gz")  
LINK=$LINK$DOWNLOAD

echo "[*] Downloading the latest version of Node.js .."

$(curl -s $LINK -o $DOWNLOAD)

echo "[*] Node.js has been downloaded .."  
echo "[*] Creating folder in /opt and unpacking Node.js there .."

$([ -d $DESTINATIONDIR ] && rm -rf $DESTINATIONDIR )
$(mkdir -p $DESTINATIONDIR)
$(tar -xf $DOWNLOAD -C $DESTINATIONDIR --strip-components=1)
$(rm $DOWNLOAD)

echo "[*] Symlinking Node.js and npm into /usr/bin .."

$([ -f /usr/bin/node ] && rm /usr/bin/node)
$([ -f /usr/bin/nodejs ] && rm /usr/bin/nodejs)
$([ -f /usr/bin/npm ] && rm /usr/bin/npm)
$(ln -s $DESTINATIONDIR/bin/node /usr/bin/node)
$(ln -s $DESTINATIONDIR/bin/node /usr/bin/nodejs)
$(ln -s $DESTINATIONDIR/bin/npm /usr/bin/npm)

echo "[*] All done!"  

I'd much rather program something like this in Python, but this actually works pretty good! I'm happy with the results 🍻

Node.js Linux Deployment Script

Tip: you can change https://nodejs.org/dist/latest/ to https://nodejs.org/dist/latest-boron/ to change the distribution channel to the latest LTS release of Node.js 😉