Command to remove all npm modules globally?

2019-01-04 04:18发布

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

标签: node.js npm
17条回答
Emotional °昔
2楼-- · 2019-01-04 04:48

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 here quickly by typing %appdata% (either in explorer, run prompt, or start menu).

查看更多
The star\"
3楼-- · 2019-01-04 04:52

For those using Powershell:

npm -gp ls --depth=0 | ForEach-Object { Get-Item $_ } | Where { $_.Name -ne 'npm' } | ForEach-Object { npm rm -g $_.Name }

To clear the cache:

npm cache clear
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-04 04:52

If you have jq installed, you can go even without grep/awk/sed:

npm ls -g --json --depth=0 |
  jq -r '.dependencies|keys-["npm"]|join("\n")' |
  xargs npm rm -g

On Debian and derived you can install jq with:

sudo apt-get install jq
查看更多
叛逆
5楼-- · 2019-01-04 04:52

sed solution

npm -gp ls | sed -r '/npm$|(node_modules.*){2,}/d; s:.*/([^/]+)$:\1:g' | xargs npm rm -g
查看更多
我只想做你的唯一
6楼-- · 2019-01-04 04:53

Well if you are on windows, and want to remove/uninstall all node_modules then you need to do following steps.

  1. Go to windows command prompt
  2. Navigate to node_modules directory (Not inside node_modules folder)
  3. Type below command and give it for 1-2 minutes it will uninstall all directories inside node_module

     rmdir /s /q node_modules
    

Hope this will help some one on windows

查看更多
爷、活的狠高调
7楼-- · 2019-01-04 04:54

OS not specified by OP. For Windows, this script can be used to nuke the local and the user's global modules and cache.

I noticed on linux that the global root is truly global to the system instead of the given user. So deleting the global root might not be a good idea for a shared system. That aside, I can port the script to bash if interested.

For Windows, save to a cmd file to run.

@ECHO OFF
SETLOCAL EnableDelayedExpansion 
SETLOCAL EnableExtensions

SET /A ecode=0

:: verify
SET /P conf="About to delete all global and local npm modules and clear the npm cache. Continue (y/[n])?
IF /I NOT "%conf%"=="y" (
  ECHO operation aborted
  SET /A ecode=!ecode!+1
  GOTO END
)

:: wipe global and local npm root
FOR %%a IN ("" "-g") DO (

  :: get root path into var
  SET cmd=npm root %%~a
  FOR /f "usebackq tokens=*" %%r IN (`!cmd!`) DO (SET npm_root=%%r)

  :: paranoid
  ECHO validating module path "!npm_root!"
  IF "!npm_root:~-12!"=="node_modules" (
    IF NOT EXIST "!npm_root!" (
      ECHO npm root does not exist "!npm_root!"
    ) ELSE (
      ECHO deleting "!npm_root!" ...
      :: delete
      RMDIR /S /Q "!npm_root!"
    )
  ) ELSE (
      ECHO suspicious npm root, ignoring "!npm_root!"
  )
)

:: clear the cache
ECHO clearing the npm cache ...
call npm cache clean

:: done
ECHO done

:END

ENDLOCAL & EXIT /b %ecode%
查看更多
登录 后发表回答