(url)
| 10 | import {Transform as Stream} from 'node:stream'; |
| 11 | |
| 12 | export function fetch(url) { |
| 13 | return new Promise(fetchPromise); |
| 14 | |
| 15 | function fetchPromise(resolve, reject) { |
| 16 | let request; |
| 17 | const protocol = new URL(url).protocol; |
| 18 | const handleResponse = getCallback.bind(null, resolve, reject); |
| 19 | if (protocol === 'https:') { |
| 20 | request = https.get(url, handleResponse); |
| 21 | } else if (protocol === 'http:') { |
| 22 | request = http.get(url, handleResponse); |
| 23 | } else { |
| 24 | reject(new Error(`Invalid protocol for url: ${url}`)); |
| 25 | return; |
| 26 | } |
| 27 | request.on('error', err => reject(err)); |
| 28 | } |
| 29 | |
| 30 | function getCallback(resolve, reject, response) { |
| 31 | if (response.statusCode !== 200) { |
| 32 | reject(new Error(`Request error: + ${response.statusCode}`)); |
| 33 | return; |
| 34 | } |
| 35 | const body = new Stream(); |
| 36 | response.on('data', chunk => body.push(chunk)); |
| 37 | response.on('end', () => resolve(body.read())); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export function atob(str) { |
| 42 | return new Buffer(str, 'base64').toString('binary'); |
no outgoing calls