UNPKG

@augment-vir/node

Version:

A collection of augments, helpers types, functions, and classes only for Node.js (backend) JavaScript environments.

27 lines (26 loc) 975 B
import { createWriteStream } from 'node:fs'; import { mkdir } from 'node:fs/promises'; import { dirname } from 'node:path'; import { Readable } from 'node:stream'; import { finished } from 'node:stream/promises'; /** * Download a file. * * @category Node : File * @category Package : @augment-vir/node * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node) */ export async function downloadFile({ url, writePath }) { const response = await fetch(url); if (!response.ok) { throw new Error(`${response.status}: ${response.statusText}`); } /** Idk how to actually trigger a response with no body. */ /* node:coverage ignore next 3 */ if (!response.body) { throw new Error(`Response body is missing from '${url}'.`); } await mkdir(dirname(writePath), { recursive: true }); const fileStream = createWriteStream(writePath); await finished(Readable.fromWeb(response.body).pipe(fileStream)); }