Setting up Node.js in Ubuntu 18.04

To install Node.js on Ubuntu 18.04:

sudo apt install nodejs

Technically that’s all you need to do but if you want to install anything as globally (npm -g) you’ll need to do so as root (e.g. using sudo).

A better way is to configure npm to use a user local path for global modules. That way global modules are stored in a directory that can be written to without needing root permission.

To configure npm to use the ~/.npm-global directory for global module:

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile
source ~/.profile

Important: If there are multiple users on the system then the above will need to be done for each of them.

Finally, update npm (need to use sudo as npm is installed in the system global path):

sudo npm install npm --global

and/or install Yarn (recommended):

npm install yarn --global