Fetch data

Concepts

  • Like browsers, Deno implements web standard APIs such as fetch.
  • Deno is secure by default, meaning explicit permission must be granted to access the network.
  • See also: Deno’s permissions model.

Overview

When building any sort of web application developers will usually need to retrieve data from somewhere else on the web. This works no differently in Deno than in any other JavaScript application, just call the fetch() method. For more information on fetch read the MDN documentation.

The exception with Deno occurs when running a script which makes a call over the web. Deno is secure by default which means access to IO (Input / Output) is prohibited. To make a call over the web Deno must be explicitly told it is ok to do so. This is achieved by adding the --allow-net flag to the deno run command.

Example

Command: deno run --allow-net fetch.ts

  1. /**
  2. * Output: JSON Data
  3. */
  4. const jsonResponse = await fetch("https://api.github.com/users/denoland");
  5. const jsonData = await jsonResponse.json();
  6. console.log(jsonData);
  7. /**
  8. * Output: HTML Data
  9. */
  10. const textResponse = await fetch("https://deno.land/");
  11. const textData = await textResponse.text();
  12. console.log(textData);
  13. /**
  14. * Output: Error Message
  15. */
  16. try {
  17. await fetch("https://does.not.exist/");
  18. } catch (error) {
  19. console.log(error);
  20. }

Files and Streams

Like in browsers, sending and receiving large files is possible thanks to the Streams API. The standard library’s streams module can be used to convert a Deno file into a writable or readable stream.

Command: deno run --allow-read --allow-write --allow-net fetch_file.ts

  1. /**
  2. * Receiving a file
  3. */
  4. import { writableStreamFromWriter } from "https://deno.land/std@$STD_VERSION/streams/mod.ts";
  5. const fileResponse = await fetch("https://deno.land/logo.svg");
  6. if (fileResponse.body) {
  7. const file = await Deno.open("./logo.svg", { write: true, create: true });
  8. const writableStream = writableStreamFromWriter(file);
  9. await fileResponse.body.pipeTo(writableStream);
  10. }
  11. /**
  12. * Sending a file
  13. */
  14. import { readableStreamFromReader } from "https://deno.land/std@$STD_VERSION/streams/mod.ts";
  15. const file = await Deno.open("./logo.svg", { read: true });
  16. const readableStream = readableStreamFromReader(file);
  17. await fetch("https://example.com/", {
  18. method: "POST",
  19. body: readableStream,
  20. });