Command to remove all npm modules globally?

The following command removes all global npm modules. Note: this does not work on Windows. For a working Windows version, see Ollie Bennett's Answer.

npm ls -gp --depth=0 | awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' | xargs npm -g rm

Here is how it works:

  • npm ls -gp --depth=0 lists all global top level modules (see the cli documentation for ls)
  • awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' prints all modules that are not actually npm itself (does not end with /npm)
  • xargs npm -g rm removes all modules globally that come over the previous pipe

sudo npm list -g --depth=0. | awk -F ' ' '{print $2}' | awk -F '@' '{print $1}'  | sudo xargs npm remove -g

worked for me

  • sudo npm list -g --depth=0. lists all top level installed
  • awk -F ' ' '{print $2}' gets rid of ├──
  • awk -F '@' '{print $1}' gets the part before '@'
  • sudo xargs npm remove -g removes the package globally

I tried Kai Sternad's solution but it seemed imperfect to me. There was a lot of special symbols left after the last awk from the deps tree itself.

So, I came up with my own modification of Kai Sternad's solution (with a little help from cashmere's idea):

npm ls -gp --depth=0 | awk -F/node_modules/ '{print $2}' | grep -vE '^(npm|)$' | xargs -r npm -g rm

npm ls -gp --depth=0 lists all globally-installed npm modules in parsable format:

/home/leonid/local/lib
/home/leonid/local/lib/node_modules/bower
/home/leonid/local/lib/node_modules/coffee-script
...

awk -F/node_modules/ '{print $2}' extracts module names from paths, forming the list of all globally-installed modules.

grep -vE '^(npm|)$' removes npm itself and blank lines.

xargs -r npm -g rm calls npm -g rm for each module in the list.

Like Kai Sternad's solution, it'll only work under *nix.


For those using Windows, the easiest way to remove all globally installed npm packages is to delete the contents of:

C:\Users\username\AppData\Roaming\npm

You can get there quickly by typing %appdata%/npm in either the explorer, run prompt, or from the start menu.

Tags:

Node.Js

Npm