* download a file using fetch API * @param {string} url * @param {string} outputPath
(url, outputPath)
| 13 | * @param {string} outputPath |
| 14 | */ |
| 15 | async function downloadFile(url, outputPath) { |
| 16 | // Use proxy if set in environment variables |
| 17 | const proxy = process.env.https_proxy || process.env.HTTPS_PROXY; |
| 18 | const agent = proxy ? new ProxyAgent(proxy) : undefined; |
| 19 | |
| 20 | const response = await fetch(url, { |
| 21 | redirect: "follow", // Automatically follow redirects |
| 22 | dispatcher: agent, |
| 23 | }); |
| 24 | |
| 25 | if (!response.ok) { |
| 26 | throw new Error(`Failed to download file, status code: ${response.status}`); |
| 27 | } |
| 28 | |
| 29 | // Create output directory if it doesn't exist |
| 30 | const outputDir = path.dirname(outputPath); |
| 31 | if (!fs.existsSync(outputDir)) { |
| 32 | fs.mkdirSync(outputDir, { recursive: true }); |
| 33 | } |
| 34 | |
| 35 | // Get the response as an array buffer and write it to the file |
| 36 | const buffer = await response.arrayBuffer(); |
| 37 | fs.writeFileSync(outputPath, Buffer.from(buffer)); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * |
no test coverage detected