(u, depth)
| 42 | validateUrl(url); |
| 43 | return new Promise((resolve, reject) => { |
| 44 | function follow(u, depth) { |
| 45 | if (depth > 5) return reject(new Error('Too many redirects')); |
| 46 | validateUrl(u); |
| 47 | https.get(u, (res) => { |
| 48 | if (res.statusCode === 301 || res.statusCode === 302) { |
| 49 | const loc = res.headers.location; |
| 50 | if (!loc) return reject(new Error('Redirect with no location')); |
| 51 | const next = loc.startsWith('/') ? new URL(loc, u).href : loc; |
| 52 | return follow(next, depth + 1); |
| 53 | } |
| 54 | if (res.statusCode !== 200) { |
| 55 | return reject(new Error(`HTTP ${res.statusCode} for ${u}`)); |
| 56 | } |
| 57 | const file = fs.createWriteStream(dest); |
| 58 | res.pipe(file); |
| 59 | file.on('finish', () => file.close(resolve)); |
| 60 | file.on('error', reject); |
| 61 | }).on('error', reject); |
| 62 | } |
| 63 | follow(url, 0); |
| 64 | }); |
| 65 | } |
no test coverage detected