Deno nuggets: Download a file in Deno
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to download a file in Deno?
~: curl https://upload.wikimedia.org/wikipedia/commons/8/84/Deno.svg -o /var/tmp/Deno.svg -s
~: ls -l /var/tmp/Deno.svg
-rw-r--r-- 1 mayankc wheel 6281 May 5 22:33 /var/tmp/Deno.svg
Solution
With the introduction of ReadableStream & WritableStream interfaces for file handling, it has become very easy to download a file using a combination of two web standard APIs:
- fetch
- pipeTo
Here is the code of a function called downloadFile, that takes two inputs: Source URL of the file & destination path of the file. The function downloads the file at the given path. If the file doesn’t exist, it’s created. If a file exists, it’s overwritten.
Here is a simple test:
// app.tsawait downloadFile(
"https://upload.wikimedia.org/wikipedia/commons/8/84/Deno.svg",
"/var/tmp/Deno1.svg",
);// --~: deno run --allow-net --allow-write=/var/tmp/ --allow-read=/var/tmp/ app.ts
~: ls -ltr /var/tmp/Deno*
-rw-r--r-- 1 mayankc wheel 6281 May 5 22:33 /var/tmp/Deno.svg
-rw-r--r-- 1 mayankc wheel 6281 May 5 22:51 /var/tmp/Deno1.svg