Eliminating the need for sudo

The npm executable can install both the local and global modules. Global modules are mostly installed to allow command line utilities to be used system wide.

On macOS and Linux, the default npm setup requires sudo access to install a module.

For example, the following will fail on a typical macOS or Linux system with the default npm setup:

npm -g install cute-stack # <-- oh oh needs sudo

This is unsuitable for several reasons. Forgetting to use sudo becomes frustrating; we're trusting npm with root access and accidentally using sudo for a local install causes permission problems (particularly with the npm local cache).

The prefix setting stores the location for globally installed modules; we can view this with the following:

npm config get prefix

Usually, the output will be /usr/local. To avoid the use of sudo, all we have to do is set ownership permissions on any subfolders in /usr/local used by npm:

sudo chown -R $(whoami) $(npm config get   
prefix)/{lib/node_modules,bin,share}

Now we can install global modules without root access:

npm -g install cute-stack # <-- now works without sudo

If changing ownership of system folders isn't feasible, we can use a second approach, which involves changing the prefix setting to a folder in our home path:

mkdir ~/npm-global
npm config set prefix ~/npm-global

We'll also need to set our PATH:

export PATH=$PATH:~/npm-global/bin
source ~/.profile

The source essentially refreshes the terminal environment to reflect the changes we've made.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset