Command to remove all npm modules globally

Is there a command to remove all global npm modules? If not, what do you suggest?


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

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.


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.