LoginSignup
0
0

More than 3 years have passed since last update.

【Deno】downloadモジュールでファイルダウンロード

Posted at

先月にkyを使用したファイルダウンロード方法を公開しましたが、コメントで

Deno にはファイルダウンロード用のモジュールがあります。
download | Deno

とご教示頂いたので、今回はその"download"モジュールを使用したファイルダウンロードを解説します。

このモジュールについて

downloadは、Denoのfetch apiをベースにしたURLからファイルをダウンロードすることができるモジュールです。

使い方

mod.tsからdownload関数をインポートして使えます。

import { download } from "https://deno.land/x/download/mod.ts";

const url =
  "https://raw.githubusercontent.com/denolib/high-res-deno-logo/master/deno_hr.png";
const fileName = "deno.png";
const dir = ".";

await download(url, { file: fileName, dir });

実行するときはネットワークにアクセスする権限と書き込み権限が必要なので、オプションに--allow-net--allow-writeを追加します。

エラー処理について

エラー処理は、try/catch文を使うか、Promisecatchが使えます。

try/catch文

import { download } from "https://deno.land/x/download/mod.ts";

const url =
  "https://raw.githubusercontent.com/denolib/high-res-deno-logo/master/deno_hr.png";
const fileName = "deno.png";
const dir = ".";

try {
  await download(url, { file: fileName, dir });
} catch (err) {
  console.error(err);
}

Promise

import { download } from "https://deno.land/x/download/mod.ts";

const url = 'https://raw.githubusercontent.com/denolib/high-res-deno-logo/master/deno_hr.png';
const fileName = "deno.png";
const dir = ".";

await download(url, { file: fileName, dir })
  .catch((err) => {
    console.error(err);
  });

やってみる

deno-download.gif

できました:relaxed:

環境

$ deno --version
deno 1.2.2
v8 8.5.216
typescript 3.9.2

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0