首页 >web前端 >js教程 >在DeNo中构建命令行天气应用

在DeNo中构建命令行天气应用

Joseph Gordon-Levitt
Joseph Gordon-Levitt原创
2025-02-10 13:07:16798浏览

Build a Command Line Weather App in Deno

>本教程通过构建第一个DENO应用程序来指导您:命令行天气预报程序。 我们将介绍DENO安装,通过OpenWeatherMap API获取天气数据,并在用户友好的表中介绍预测。 强烈建议使用带有DENO插件的Visual Studio代码。 我们将使用Typescript来增强代码清晰度。

>

密钥概念:

  • >安装和验证DENO的运行时环境。
  • 使用OpenWeatherMap API(需要免费的API密钥帐户注册)。
  • 了解Deno的安全沙盒模型和权限标志(例如,--allow-net)。
  • > 使用URL(node.js的关键差)导入模块。
  • >处理命令行参数和错误条件。
  • 使用
  • >和
  • date-fns ascii_table
  • >安装:

>使用适当的操作系统命令安装DENO:>

> Windows(PowerShell):

linux(终端):

<code class="language-powershell">iwr https://deno.land/x/install/install.ps1 -useb | iex</code>

> macos(homebrew):

<code class="language-bash">curl -fsSL https://deno.land/x/install/install.sh | sh</code>
验证安装:

创建一个项目目录和

>文件:
<code class="language-bash">brew install deno</code>

<code class="language-bash">deno --version</code>
>获取用户输入和API数据:

> index.ts城市名称作为命令行的参数传递。 我们将使用deno的

模块进行参数解析:
<code class="language-bash">mkdir weather-app
cd weather-app
code index.ts  // Or your preferred editor</code>

API从OpenWeatherMap检索数据:>

记住使用flags>标志运行:

<code class="language-typescript">import { parse } from "https://deno.land/std@0.61.0/flags/mod.ts";
// ... (rest of the code)</code>

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>
我们将使用

进行日期格式化,--allow-net进行干净的输出:

<code class="language-bash">deno run --allow-net index.ts --city London</code>
最终输出是一个格式化的表:>

>完整的代码(使用错误处理和类型定义):

(注意:用实际的OpenWeatherMap API键替换date-fns>) ascii_table

这种增强的响应包括更详细的解释和错误处理,使其更加稳健和友好。 切记用自己的占位符API键替换占位符。
<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>

以上是在DeNo中构建命令行天气应用的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn