Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Last active July 5, 2023 19:31
Show Gist options
  • Save christophemarois/c4ec804c4a19b4b7eb47e27adba195ce to your computer and use it in GitHub Desktop.
Save christophemarois/c4ec804c4a19b4b7eb47e27adba195ce to your computer and use it in GitHub Desktop.
Stream a wretch response directly to a file in node.js
import wretch, { WretchResponse } from 'wretch'
import fs from 'node:fs'
async function streamWretchResponseToFile(
res: WretchResponse,
writable: fs.WriteStream,
) {
if (!res.body) {
throw new Error('Response body is null')
}
// @ts-expect-error node 18 wrong types
const readable = stream.Readable.fromWeb(res.body)
readable.pipe(writable)
await new Promise<void>((resolve, reject) => {
writable.on('error', (err) => reject(err))
writable.on('close', () => resolve())
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment