Skip to content

Instantly share code, notes, and snippets.

@xiaoyvr
Last active November 20, 2017 14:35
Show Gist options
  • Save xiaoyvr/c329de3d32b516de0c56d03de6993891 to your computer and use it in GitHub Desktop.
Save xiaoyvr/c329de3d32b516de0c56d03de6993891 to your computer and use it in GitHub Desktop.

Manage Node Version in Windows

Require scoop to be installed. Then put these in your $profile, you will get different nodejs for different powershell session.

function Set-LocationWithNodeVersion ($dir){
	Set-Location $dir
	if (Test-Path '.\package.json') {
		$json = Get-Content '.\package.json' | ConvertFrom-Json
		$version = $json.engines.node
		if (-not $version) {
			if (Test-Path '.\node-version') {
				$version = (Get-Content '.\node-version').trim()
			}
		}

		if ($version) {
			Set-CurrentNodeVersion($version)
		}
	}
}

function Set-CurrentNodeVersion($version) {
	$nodeDir = "$($env:USERPROFILE)\scoop\apps\nodejs"
	if (Test-Path "$nodeDir\$version") {
		$currentVersion = (& node --version).Substring(1)
		Write-Host "Switching nodejs version from $currentVersion to $version"
		$nodeDir = "$($env:USERPROFILE)\scoop\apps\nodejs"
		$newPaths = $env:Path.Split(';') | ? {
			-not $_.StartsWith($nodeDir)
		}
		$newPaths += @("C:\Users\xiaoqia\scoop\apps\nodejs\$version",
			"C:\Users\xiaoqia\scoop\apps\nodejs\$version\bin")
		$env:Path = $newPaths -Join ";"
	} else {
		Write-Host "Nodejs@$version is not installed."
	}
}

Set-Alias cd Set-LocationWithNodeVersion -Option AllScope
Set-Alias nvm-use Set-CurrentNodeVersion -Option AllScope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment