Skip to content

Instantly share code, notes, and snippets.

@danopia
Created November 8, 2020 09:44
Show Gist options
  • Save danopia/1a91ea95882254872f50eb2d62210657 to your computer and use it in GitHub Desktop.
Save danopia/1a91ea95882254872f50eb2d62210657 to your computer and use it in GitHub Desktop.
Small Deno sample of downloading a binary file into a data URL
import * as Base64 from 'https://deno.land/[email protected]/encoding/base64.ts';
async function toDataUrl(resp: Response): Promise<string> {
const contentType = resp.headers.get('content-type') ?? 'application/octet-stream';
const buffer = await resp.arrayBuffer();
return `data:${contentType};base64,`+Base64.encode(buffer);
}
const gifUrl = 'https://matthews.sites.wfu.edu/misc/jpg_vs_gif/testImage.gif';
console.log(await fetch(gifUrl).then(toDataUrl));
@danopia
Copy link
Author

danopia commented Nov 8, 2020

To address the mix of await and then:

// wait for the result of fetching this URL and then building a data URL
await fetch(gifUrl).then(toDataUrl);

// vs

// wait for the result of building a data URL out of the waited-for result of fetching this URL
await toDataUrl(await fetch(gifUrl));

Just a personal preference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment