How to install NodeJS from sources in a specific directory

First of all, you need to update repositories, and make sure you have all the needed packages ready and installed:

sudo apt-get update
sudo apt-get install build-essential openssl libssl-dev pkg-config 

Then, you can retrieve the sources from the official NodeJS website by downloading the “Source Code” (here, it’s version 5.0.0):

sudo mkdir /opt/node/
cd /opt/node/
sudo wget https://nodejs.org/dist/v5.0.0/node-v5.0.0.tar.gz

Once downloaded, you can extract it in /opt/ directory for example (where it has been downloaded):

cd /opt/node/
sudo tar -xzvf node-v5.0.0.tar.gz

You can now open the new directory to compile and install NodeJS from sources:

cd node-v5.0.0/
sudo ./configure
sudo make
sudo make install

Your binaries (npm, node, …) are now available in /opt/node/bin/ directory.

Later, if you need to upgrade NodeJS you just installed, you will only need to download the latest version inside the same directory, extract the content in there and perform same installation process.