Avoiding sudo
It should be self-evident that providing your scripts sudo permissions is a bad idea. From concerns about third-party packages, missing security layers in your code to access issues and inconveniences - it would be too much to talk about the possible dangers. Let's just agree that running via sudo is not an option.
One of my most-used utilities is neoan3-cli. Even if I am not using neoan3, the migration and credential handling is always welcome.
AWS Ubuntu instance
One of the most versatile hosting solutions is still Amazon's EC2 instances. While Amazon's Linux version seems to be the logical step, I am simply feeling more at ease with Ubuntu and am frankly a little skeptical about a distro that seems so coupled with a hosting solution (As far as I understand, the distro started out as a customization of CentOS and then branched into its own beast). Ubuntu is the perfect solution as everything we are going to talk about will be independent from your hosting solution. We are using version 18.04 but there shouldn't be any differences to prior versions in our scenario.
NOTE: On AWS your username will likely be "ubuntu" in our scenario.
The directory of global npm packages
The first thing we want to do is creating a directory within our user's home. On Ubuntu, this should be /home/USERNAME/
( or ~/
). We will want to create a directory for our global packages:
mkdir ~/.npm-packages
Next, let's set up npm to use this directory:
npm config set prefix "${HOME}/.npm-packages"
PATH variable
In order for node & npm to find installed packages, we should add this directory to the PATH variable. On a server you might want to do this via nano ~/.bashrc
.
Add the following lines:
NPM_STORE="${HOME}/.npm-packages"
export PATH="$PATH:$NPM_STORE/bin"
# Make sure this line is the last in the config (in case you defined MANPATH already)
# Otherwise, fall back to `manpath` so we can inherit from `/etc/manpath`.
export MANPATH="${MANPATH-$(manpath)}:$NPM_STORE/share/man"
Let's try it out
Assuming everything went as planned, we should now be able to use global packages without the root user or sudo. Start a new terminal window (or restart your ssh connection) and try: npm i -g neoan3-cli
. After successful installation, the command neoan3 -v
should output the installed version.
Final thoughts
There is a popular script out there automating this process here. Please be aware that this solution does not play well with node version manager. Otherwise it is a solid solution with many happy users.
Top comments (0)