Mar 2, 2017

Configure npm To Install Packages Globally Without sudo Using A Script

npm logo

npm is the default package manager for Node.js. It consists of a command line client that integrates with a remote registry, and it makes it easy to install, share and distribute code.

If you're using npm installed from a repository in Linux (like the official Ubuntu or Node.js repositories), you may have noticed that you can't install packages globally ("-g") as a regular user. Many websites mention installing npm packages using sudo, but this messes up some permissions and is not recommended.

The easiest way to get npm to download packages globally without sudo ("npm install -g <package>") in Linux is to use a script, called npm-g_nosudo, to automatically set everything up.

The script GitHub page mentions that it was tested on Ubuntu 14.04 with Bash, but I don't see why it wouldn't work in other Linux distributions.

As an alternative, you can use THESE instructions to set up npm to install packages globally without sudo in Linux.

Here's what the npm-g_nosudo script does:
  • creates a backup list of your installed npm packages and removes all but npm;
  • then it creates a local directory and configures node to use this for global installs (~/.npm-packages); this (optionally) includes adding the local directory and bin paths to ~/.bashrc or ~/.zsh;
  • it fixes permissions for the ~/.npm directory;
  • and finally, it reinstalls the old packages.

The reason behind publishing this article is to be able to link to it in future posts that mention installing npm packages, to make it easy for users to install them the recommended way - without sudo.

Another way of installing packages with npm in Linux without sudo is by using NVM to install Node.js, instead of a repository.

Configure npm to install packages globally without sudo on Linux (using npm-g_nosudo)

Before proceeding, it's important to mention that you should never run scripts without understanding what they do. So take a look at the npm-g_nosudo script before running it!

To download the npm-g_nosudo script and run it, use the following commands:
cd && wget
chmod +x

The script will ask you to choose the install directory - you can press ENTER to use the default directory (~/.npm-packages). The second and final step is to choose if if you want to update ~/.bashrc and ~/.zsh with the new paths - type "y" and press ENTER to do this automatically, or "n" to perform these changes manually.

Once you're done, remember to source ~/.bashrc or ~/.zsh, depending on what you use (or launch a new terminal):
- for Bash:
source ~/.bashrc
- for Zsh:
source ~/.zsh

via Web Upd8 - Ubuntu / Linux blog