跳至主要內容

取得資料

概念

  • 與瀏覽器一樣,Deno 實作了網路標準 API,例如 fetch
  • Deno 預設為安全,表示必須授予明確的權限才能存取網路。
  • 另請參閱:Deno 的 權限 模型。

概觀

在建置網路應用程式時,開發人員通常需要從網路上的其他地方擷取資料。這在 Deno 中與在任何其他 JavaScript 應用程式中沒有不同,使用 fetch() 方法。如需更多資訊,請閱讀 MDN fetch 文件

Deno 的差異發生在執行透過網路呼叫的指令碼時。Deno 預設為安全,表示預設禁止存取 IO(輸入/輸出)。若要透過網路呼叫,必須明確告知 Deno 可以執行此動作。這是透過將 --allow-net 旗標新增到 deno run 指令來達成。

範例

指令: deno run --allow-net fetch.ts

/**
* Output: JSON Data
*/
const jsonResponse = await fetch("https://api.github.com/users/denoland");
const jsonData = await jsonResponse.json();

console.log(jsonData);

/**
* Output: HTML Data
*/
const textResponse = await fetch("https://deno.land/");
const textData = await textResponse.text();

console.log(textData);

/**
* Output: Error Message
*/
try {
await fetch("https://does.not.exist/");
} catch (error) {
console.log(error);
}

檔案和串流

與瀏覽器類似,傳送和接收大型檔案是透過 Streams API 實現。 Deno.FsFile API 提供兩個屬性: readablewritable,可用於將 Deno 檔案轉換為可寫入或可讀取的串流。

指令: deno run --allow-read --allow-write --allow-net fetch_file.ts

/**
* Receiving a file
*/
const fileResponse = await fetch("https://deno.land/logo.svg");

if (fileResponse.body) {
const file = await Deno.open("./logo.svg", { write: true, create: true });

await fileResponse.body.pipeTo(file.writable);
}

/**
* Sending a file
*/
const file = await Deno.open("./logo.svg", { read: true });

await fetch("https://example.com/", {
method: "POST",
body: file.readable,
});