Rumah >hujung hadapan web >tutorial js >Bina aplikasi cuaca baris arahan di Deno
Konsep Utama:
--allow-net
date-fns
. ascii_table
Pemasangan:
Pasang Deno menggunakan arahan yang sesuai untuk sistem pengendalian anda:
Windows (PowerShell):
<code class="language-powershell">iwr https://deno.land/x/install/install.ps1 -useb | iex</code>
linux (terminal):
<code class="language-bash">curl -fsSL https://deno.land/x/install/install.sh | sh</code>
macOS (homebrew):
<code class="language-bash">brew install deno</code>Sahkan pemasangan:
<code class="language-bash">deno --version</code>Buat direktori projek dan
fail: index.ts
<code class="language-bash">mkdir weather-app cd weather-app code index.ts // Or your preferred editor</code>
mengambil input pengguna dan data API:
Nama bandar diluluskan sebagai hujah baris arahan. Kami akan menggunakan modul Deno untuk parsing argumen: flags
<code class="language-typescript">import { parse } from "https://deno.land/std@0.61.0/flags/mod.ts"; // ... (rest of the code)</code>API
mengambil data dari OpenWeatherMap: fetch
<code class="language-typescript">// ... (API key and other code) const res = await fetch( `https://api.openweathermap.org/data/2.5/forecast?q=${args.city}&units=metric&appid=${apiKey}`, ); const data = await res.json(); // ... (error handling and data processing)</code>ingat untuk berlari dengan bendera
: --allow-net
<code class="language-bash">deno run --allow-net index.ts --city London</code>
Pemprosesan Data dan Pembentangan:
untuk output bersih: date-fns
ascii_table
<code class="language-typescript">import { fromUnixTime, format } from "https://deno.land/x/date_fns@v2.15.0/index.js"; import AsciiTable from "https://deno.land/x/ascii_table/mod.ts"; // ... (data processing using interfaces and functions)</code>
<code class="language-typescript">// ... (table creation and display) console.log(table.toString());</code>Kod Lengkap (dengan pengendalian ralat dan definisi jenis):
(nota: ganti dengan kunci API OpenWeatherMap sebenar anda.) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
<code class="language-typescript">// ... (imports as shown above) // ... (argument parsing and error handling as shown above) const apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const res = await fetch( `https://api.openweathermap.org/data/2.5/forecast?q=${args.city}&units=metric&appid=${apiKey}`, ); if (!res.ok) { console.error(`Error fetching weather data: ${res.status} ${res.statusText}`); Deno.exit(1); } const data = await res.json(); // ... (Interface definition and data processing as shown in the previous sections) // ... (table creation and display as shown in the previous sections)</code>
Atas ialah kandungan terperinci Bina aplikasi cuaca baris arahan di Deno. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!