-
Notifications
You must be signed in to change notification settings - Fork 23
/
fetch-cert.js
39 lines (31 loc) · 1.15 KB
/
fetch-cert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import https from 'https'
const globalCache = { } // default in-memory cache for downloaded certificates
export default function fetchCert (options, callback) {
const url = options.url
const cache = options.cache || globalCache
const cachedResponse = cache[url.href]
let servedFromCache = false
if (cachedResponse) {
servedFromCache = true
process.nextTick(callback, undefined, cachedResponse, servedFromCache)
return
}
let body = ''
https.get(url.href, function (response) {
if (!response || 200 !== response.statusCode) {
const statusCode = response ? response.statusCode : 0
return callback('Failed to download certificate at: ' + url.href + '. Response code: ' + statusCode)
}
response.setEncoding('utf8')
response.on('data', function (chunk) {
body += chunk
})
response.on('end', function () {
cache[url.href] = body
callback(undefined, body, servedFromCache)
})
})
.on('error', function (er) {
callback('Failed to download certificate at: ' + url.href +'. Error: ' + er)
})
}