Skip to content

Instantly share code, notes, and snippets.

@rivy
Forked from johnmcase/updateNpm.bat
Last active November 5, 2022 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rivy/c69563af410d8e8e6e105e5554578fc8 to your computer and use it in GitHub Desktop.
Save rivy/c69563af410d8e8e6e105e5554578fc8 to your computer and use it in GitHub Desktop.
Update npm on windows
@setLocal EnableDelayedExpansion
@echo off
:: from <https://gist.github.com/rivy/c69563af410d8e8e6e105e5554578fc8>; cloned from https://github.com/coreybutler/nvm-windows/issues/300
set wanted_version=%~1
if NOT DEFINED wanted_version ( set "wanted_version=latest" )
if "!wanted_version!" == "latest" (
for /f %%i in ('npm show npm version') do set wanted_version=%%i
)
for /f %%i in ('npm -g -v') do set cur_version=%%i
if "!cur_version!" == "!wanted_version!" (
echo Already on npm version !wanted_version!.
) else (
echo Updating to !wanted_version!...
for /f %%g in ('npm config get prefix') do set node_path=%%g
rename "!node_path!\npm" npm2
rename "!node_path!\npm.cmd" npm2.cmd
rename "!node_path!\npm.ps1" npm2.ps1
rename "!node_path!\node_modules\npm" npm2
if EXIST "!node_path!\npx" rename "!node_path!\npx" npx2
if EXIST "!node_path!\npx.cmd" rename "!node_path!\npx.cmd" npx2.cmd
if EXIST "!node_path!\npx.ps1" rename "!node_path!\npx.ps1" npx2.ps1
node "!node_path!\node_modules\npm2\bin\npm-cli.js" i npm@!wanted_version! -g
for /f %%i in ('npm -g -v') do set new_version=%%i
echo New version installed is !new_version!
if "!new_version!" == "!wanted_version!" (
echo Successfully updated to !wanted_version!. Cleaning up backups...
del "!node_path!\npm2"
del "!node_path!\npm2.cmd"
del "!node_path!\npm2.ps1"
@RD /S /Q "!node_path!\node_modules\npm2"
if EXIST "!node_path!\npx2" del "!node_path!\npx2"
if EXIST "!node_path!\npx2.cmd" del "!node_path!\npx2.cmd"
if EXIST "!node_path!\npx2.ps1" del "!node_path!\npx2.ps1"
echo Update complete.
) else (
echo Something went wrong. Rolling back.
if exist "!node_path!\npm" (
del "!node_path!\npm"
)
if exist "!node_path!\npm.cmd" (
del "!node_path!\npm.cmd"
)
if exist "!node_path!\npm.ps1" (
del "!node_path!\npm.ps1"
)
if exist "!node_path!\node_modules\npm" (
@RD /S /Q "!node_path!\node_modules\npm"
)
if exist "!node_path!\npx" (
del "!node_path!\npx"
)
if exist "!node_path!\npx.cmd" (
del "!node_path!\npx.cmd"
)
if exist "!node_path!\npx.ps1" (
del "!node_path!\npx.ps1"
)
rename "!node_path!\npm2" npm
rename "!node_path!\npm2.cmd" npm.cmd
rename "!node_path!\npm2.ps1" npm.ps1
rename "!node_path!\node_modules\npm2" npm
if EXIST "!node_path!\npx2" rename "!node_path!\npx2" npx
if EXIST "!node_path!\npx2.cmd" rename "!node_path!\npx2.cmd" npx.cmd
if EXIST "!node_path!\npx2.ps1" rename "!node_path!\npx2.ps1" npx.ps1
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment