Last active
February 4, 2016 14:23
-
-
Save DimitarChristoff/6d53cb23299219d86d14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var https = require('https'), | |
http = require('http'), | |
path = require('path'), | |
unzip = require('unzip'), | |
parse = require('url').parse, | |
q = require('q'); | |
function download(url, writePath){ | |
var deffered = q.defer(), | |
isHttps, | |
downloadStream, | |
env = process.env, | |
HTTP_PROXY = env.HTTP_PROXY || env.http_proxy, | |
HTTPS_PROXY = env.HTTPS_PROXY || env.https_proxy, | |
parsed; | |
// prevent proxy errors | |
if (HTTP_PROXY || HTTPS_PROXY){ | |
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; | |
} | |
function setProxy(proxyString, options){ | |
if (proxyString){ | |
parsed = parse(proxyString); | |
options.host = parsed.hostname; | |
parsed.port && (options.port = parsed.port); | |
parsed.auth && (options.auth = parsed.auth); | |
} | |
return options; | |
} | |
function onError(err){ | |
if (isHttps){ | |
console.log('HTTPS download failed, trying http'); | |
getRvm(url.replace('https', 'http')); | |
} else { | |
deffered.reject(new Error(err)); | |
} | |
} | |
function getRvm(rvmUrl){ | |
isHttps = rvmUrl.lastIndexOf('https') >= 0; | |
downloadStream = isHttps ? https : http; | |
var options = setProxy(isHttps ? HTTPS_PROXY : HTTP_PROXY, { | |
path: rvmUrl, | |
agent: false, | |
method: 'GET' | |
}); | |
downloadStream.request(options, function(response){ | |
if (response.statusCode !== 200){ | |
onError('Download Failed'); | |
} else { | |
response.pipe(unzip.Extract({ | |
path: path.dirname(writePath) | |
})).on('close', function(){ | |
deffered.resolve(); | |
}); | |
} | |
}).on('error', onError).on('response', function(data){ | |
console.log('Download in progres...' /*, data.headers*/); | |
}); | |
} | |
getRvm(url); | |
return deffered.promise; | |
} | |
module.exports = { | |
download: download | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment