Skip to content

Instantly share code, notes, and snippets.

@zhilich
Last active November 6, 2017 03:26
Show Gist options
  • Save zhilich/1820bb106e9706ff2fc09dadd0aa5166 to your computer and use it in GitHub Desktop.
Save zhilich/1820bb106e9706ff2fc09dadd0aa5166 to your computer and use it in GitHub Desktop.
npm3 custom cache
# This is a custom implementation of npm cache.
# It is significantly faster then original implementation and restores packages almost instantaneously.
$ErrorActionPreference = "Stop"
if (-not (Test-Path ".\node_modules")) {
Write-Host "node_modules folder is missing. Creating cache entry and junction point correspondingly."
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
# Calculating hash from package.json. We are using it as a key in our cache.
# todo: Currently we assume that there will be no collisions in MD5 cache. Ideally we should store package.json in cache and perform full comparison between files.
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes("package.json")))
Write-Host "Md5 from package.json: $($hash)"
# Cache is stored globally in %APPDATA% folder.
$npmCacheFolder = "$($env:APPDATA)\npm-quick-cache\$($hash)\node_modules"
New-Item -ItemType Directory -Force -Path $npmCacheFolder
# Creating junction point.
cmd /c mklink /j "node_modules" $npmCacheFolder
if (-not $?) {
throw "Failed to create junction point.";
}
}
$npmInstalledMarker = ".\.npm_installed";
# Performance optimization. it takes 9 seconds for npm to verify dependencies. We are creating folder that indicates that installation was performed already.
if (-not (Test-Path -LiteralPath $npmInstalledMarker)) {
# Install [email protected] if required ([email protected] the most stable version in the moment)
$npm = Test-Path -LiteralPath ".\node_modules\.bin\npm"
npm install [email protected]
if (-not $?) {
throw "Npm Install failed";
}
# Install node packages
.\node_modules\.bin\npm install
if (-not $?) {
throw "Npm install failed";
}
New-Item -ItemType Directory -Force -Path $npmInstalledMarker
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment