Skip to content

Instantly share code, notes, and snippets.

@manuelbieh
Last active August 26, 2022 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelbieh/e44c3a2c0586d4df05f9c03b9060c75e to your computer and use it in GitHub Desktop.
Save manuelbieh/e44c3a2c0586d4df05f9c03b9060c75e to your computer and use it in GitHub Desktop.
Deno File Download

Use Deno to download files from the internet.

Usage

deno run --allow-net --allow-write download.ts [url] [filename]

Example

 deno run --allow-net --allow-write \
   https://gist.githubusercontent.com/manuelbieh/e44c3a2c0586d4df05f9c03b9060c75e/raw/32c5b224d0b33b44825e6c47856263541027a05a/download.ts \
   https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png \
   google-logo.png
const download = async (url: string, filename: string) => {
const data = (await fetch(url)).arrayBuffer();
console.log(`Saving ${url} to ${filename}`);
return Deno.writeFile(filename, new Uint8Array(await data));
};
const [url, filename] = Deno.args;
if (!url || !filename) {
throw new Error('url or filename is missing.');
}
await download(url, filename);
@asins
Copy link

asins commented Jan 18, 2021

@kouseralamin
Copy link

Here is one with progress indicator. If anyone is interested.

const url = "https://storage.googleapis.com/cloud-samples-data/speech/listen/Alice_FC.flac"; // file source

fetch(url).then(function (value) {
  const total = Number(value.headers.get("content-length") ? value.headers.get("content-length") : 0);
  new Response(
    new ReadableStream({
      async start(controller) {
        const reader = value.clone().body!.getReader();
        let loaded = 0;
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          loaded += value.byteLength;
          console.log(loaded/total);
        }
        controller.close();
      },
    }),
  );
  return value.arrayBuffer();
}).then(function (value) {
  Deno.writeFile("./a.flac", new Uint8Array(value)); // FileName is a.flac
}).catch(function(e) {
  console.error(e);
});

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