Skip to content

Instantly share code, notes, and snippets.

@Flet
Created July 10, 2014 23:23
Show Gist options
  • Save Flet/5bf4f31517ef37da4653 to your computer and use it in GitHub Desktop.
Save Flet/5bf4f31517ef37da4653 to your computer and use it in GitHub Desktop.
Avoiding `sudo npm` on Ubuntu

I've found the best way around needing sudo for global npm installs in Ubuntu is to use an .npmrc file and set a prefix for where npm installs things, then add that location to your PATH. This allows you to npm -g without sudo. With this setup I'm running ampersand's CLI without issue (and avoiding the need to sudo npm in general).

If you have any global modules installed, they should be uninstalled first so they are removed from the PATH. List all globally installed npm modules by running:

sudo npm -g ls -depth 0

Record them somewhere so you can reinstall them later :)

Run this command to automagically remove all globally installed modules

sudo npm -g ls -depth 0  -parseable true | grep node | xargs -n 1 basename | xargs npm -g rm

Now everything is nice and clean. Let's set up npm to avoid sudo!

# set up prefix for .npmrc -- this will put all npm's stuff in a dir called "npm" in home directory
echo prefix = ~/npm >> ~/.npmrc

# update npm! this requires sudo... 
# this step is important as there is a bug in 1.4.14 that makes it ignore the prefix setting
sudo npm update npm -g
# clear npm cache to get rid of things with root access
sudo npm cache clean

# install ampersand globally -- without sudo!
npm install -g ampersand

# update .profile to include npm/bin in PATH (or do this manually wherever you maintain your path)
echo export PATH=\$PATH:\~/npm/bin >> .profile
. ~/.profile

# now ampersand should map to the new place
which ampersand

@chumaumenze
Copy link

chumaumenze commented May 24, 2018

Thanks for this. I was getting permission denied. Simply prepend sudo to the last command fixed it.

sudo npm -g ls -depth 0 -parseable true | grep node | xargs -n 1 basename | sudo xargs npm -g rm

Use sudo npm install npm -g to update npm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment