Deno.js Tutorial to Download Image or PDF File From URL Using Fetch API in TypeScript Full Project For Beginners

 

 

Deno fetch api based module to download file from a URL.

 

Import

 

 

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

 

 

Usage

 

 

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

const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';

try {
    const fileObj = await download(url);
} catch (err) {
    console.log(err)
}

 

 

DOWLOADING PDF FILE

 

 

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

const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';

download(url)
  .then(fileObj => {
    console.log(fileObj)
  })
  .catch(err => {
    console.log(err)
  });

 

 

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

const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';

try {
    // NOTE : You need to ensure that the directory you pass exists.
    const destination: Destination = {
        file: 'example.pdf',
        dir: './test'
    }
    /* sample with mode
     const destination: Destination = {
        file: 'example.pdf',
        dir: './test',
        mode: 0o777
    }
    */
    const fileObj = await download(url, destination);
} catch (err) {
    console.log(err)
}

 

 

 

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

const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';

try {
    const destination: Destination = {}
    const reqInit: RequestInit = {
        method: 'GET'
    }
    /* sample with mode
     const destination: Destination = {
        file: 'example.pdf',
        dir: './test',
        mode: 0o777
    }
    */
    const fileObj = await download(url, destination, reqInit);
} catch (err) {
    console.log(err)
}

 

See also  Deno.js Caching Tutorial to Cache App or Data inside App Using deno-cache Library in TypeScript Full Project For Beginners

 

Return Value

 

download function returns an object with attributes: file(filename), dirfullPath, and size(in bytes)

 

// definiton of return object. check:./type.ts
DownlodedFile {
  file: string,
  dir:string,
  fullPath: string,
  size: number
}

Deno Permission

 

You need --allow-net and --allow-write permission to use download function.

Leave a Reply