How to npm install global not as root? How to npm install global not as root? shell shell

How to npm install global not as root?


Sindre Sorhus has a great guide at github.com/sindresorhus/guides which I've reposted here.


Install npm packages globally without sudo on OS X and Linux

npm installs packages locally within your projects by default. You can also install packages globally (e.g. npm install -g <package>) (useful for command-line apps). However the downside of this is that you need to be root (or use sudo) to be able to install globally.

Here is a way to install packages globally for a given user.

1. Create a directory for your global packages

mkdir "${HOME}/.npm-packages"

2. Reference this directory for future usage in your .bashrc/.zshrc:

NPM_PACKAGES="${HOME}/.npm-packages"

3. Indicate to npm where to store your globally installed package. In your $HOME/.npmrc file add:

prefix=${HOME}/.npm-packages

4. Ensure node will find them. Add the following to your .bashrc/.zshrc:

NODE_PATH="$NPM_PACKAGES/lib/node_modules:$NODE_PATH"

5. Ensure you'll find installed binaries and man pages. Add the following to your .bashrc/.zshrc:

PATH="$NPM_PACKAGES/bin:$PATH"# Unset manpath so we can inherit from /etc/manpath via the `manpath`# commandunset MANPATH # delete if you already modified MANPATH elsewhere in your configMANPATH="$NPM_PACKAGES/share/man:$(manpath)"

Check out npm-g_nosudo for doing the above steps automagically


NOTE: If you are running OS X, the .bashrc file may not yet exist, and the terminal will be obtaining its environment parameters from another file, such as .profile or .bash_profile. These files also reside in the user's home folder. In this case, simply adding the following line to them will instruct Terminal to also load the .bashrc file:

source ~/.bashrc


Many setups already expect binaries to be found in ~/.local/bin/. So this answer follows that convention. Other files will get installed to ~/.local/lib/node_modules/.

1. Configure npm

Run:

npm config set prefix '~/.local/'

This modifies ~/.npmrc to include this line:

prefix=~/.local/

2. Make sure ~/.local/bin exists and is in your PATH

Run echo "$PATH" to have a look at your path. If it does not include ~/.local/bin/ already, you will need to configure your system to include it.

mkdir -p ~/.local/binecho 'export PATH=~/.local/bin/:$PATH' >> ~/.bashrc

Replace .bashrc with the configuration file of the shell that you are using.

3. Install packages globally

npm install -g packagename


Unless you require a package installation due to dependencies, which are rare, I would recommend you use NVM (https://github.com/creationix/nvm) to install Node.

If you do this without sudo, you will also not need to use sudo when globally installing modules.