Skip to content

Instantly share code, notes, and snippets.

@cannap
Created September 21, 2018 14:49
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 cannap/8da8e8df9fb5afaa8c933b3e62847917 to your computer and use it in GitHub Desktop.
Save cannap/8da8e8df9fb5afaa8c933b3e62847917 to your computer and use it in GitHub Desktop.
# Automate npm updating when using nvm-windows
# Installs npm@latest for the current active node install
# Source: https://github.com/coreybutler/nvm-windows/issues/300#issuecomment-368192283
$ErrorActionPreference = "Stop"
# Create a folder in the Temp directory and return it
# Source: https://stackoverflow.com/a/34559554/9165387
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
$name = [System.IO.Path]::GetRandomFileName()
New-Item -ItemType Directory -Path (Join-Path $parent $name)
}
# Test for PowerShell version 6 or greater
if ($PSVersionTable.PSVersion.Major -lt 6) {
throw "This script is compatible with PowerShell version >=6.0 (detected $($PSVersionTable.PSVersion.ToString()))."
}
# Get the path to the active node install from nvm
$currentVer = (
nvm list | ForEach-Object {[regex]::Match($_, "\* (\d+\.\d+.\d+)")} |
Where-Object Success | ForEach-Object {"v" + $_.Captures.Groups[1].Value} |
Select-Object -First 1
)
$nvmRoot = (
nvm root | ForEach-Object {[regex]::Match($_, "Current Root: (.+)")} |
Where-Object Success | ForEach-Object {$_.Captures.Groups[1].Value} |
Select-Object -First 1
)
$nodeInstallPath = Join-Path $nvmRoot $currentVer
if (-not (Test-Path $nodeInstallPath)) {
throw [System.IO.FileNotFoundException] "Test-Path : `"$nodeInstallPath`" does not exist."
}
# Create a temp directory and move the node_modules\npm dir into it
$tempDir = New-TemporaryDirectory
Write-Output "Moving `"$(Join-Path $nodeInstallPath "node_modules" "npm")`" to `"$tempDir`"..."
Move-Item $(Join-Path $nodeInstallPath "node_modules" "npm") $tempDir
# Delete the npm and npm.cmd files from the node folder
Write-Output "Removing `"npm`" and `"npm.cmd`" from `"$nodeInstallPath`"..."
Remove-Item $(Join-Path $nodeInstallPath "npm*")
$tempNpmBinDir = Join-Path $tempDir "npm" "bin"
if (-not (Test-Path $tempNpmBinDir)) {
throw [System.IO.FileNotFoundException] "Test-Path : `"$tempNpmBinDir`" does not exist."
}
# Run the install script from the temp folder
Write-Output "Running `"node npm-cli.js i npm@latest -g`" from `"$tempNpmBinDir`"..."
node $(Join-Path $tempNpmBinDir "npm-cli.js") i npm@latest -g
# Delete the temp folder once complete
Write-Output "Cleanup..."
Remove-Item $tempDir -Recurse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment