Deno gets the weather for a specified or IP-based city

A TS script that runs directly with deno to get 7-day weather forecasts for specified or ip-based cities.

demo

Deno run --allow-net index.ts --city HangzhouCopy the code

grammar

deno run --allow-net index.ts [--city xxx]
Copy the code

Parameter description (parameters are prefixed with –) :

  • Deno run index.ts: run the index.ts file using deno
  • –allow-net: allows TS files to initiate network requests
  • –city XXX: [Optional] Specify the city name, if not specified, obtain the IP-based city

The tutorial

Environment required: Nodejs

Install denO globally

yarn global add deno
Copy the code

The first deno script

mkdir my-deno
cd my-deno
echo "console.log('Hello deno! ')"> index.ts
Copy the code

Explanation:

  • Create a new folder
  • Go to this folder
  • Write a line of code to the new TS file

Create a terminal in this folder and run it

deno run index.ts
Copy the code

The output

Hello deno!
Copy the code

Gets command line arguments

Modified index. Ts

import { parse } from "https://deno.land/[email protected]/flags/mod.ts";

/** Get the city input */
const args = parse(Deno.args);
const city = args.city;
let isCitySeted = false;
if (typeof city === "string") {
  isCitySeted = true;
  console.log("Designated city:", city);
} else {
  console.log("Designated city:"."IP location-based city");
}
Copy the code

Explanation:

  • Introduce formatting methods in the network library
  • Deno.args takes command line arguments and formats them into objects
  • Gets the entered city name
  • Check whether the city input is correctly obtained

Create a terminal in this folder and run it

Deno run --allow-net index.ts --city HangzhouCopy the code

Parameters:

  • – allow – net: namely--allow-net trueTo enable the network request permission
  • Hangzhou: The name of the designated city is Hangzhou

Output:

Check file:///xxx/index.tsCopy the code

Querying the Weather API

Tianqiapi.com is available as a free weather API to obtain forecast data. Just sign up for a free account with your mailbox to get an API key. API document address

Free 7-day weather interface request method and URL:

  • Request method:GET
  • Interface address:https://tianqiapi.com/api

Sample request

https://tianqiapi.com/api?version=v1&appid=65573146&appsecret=dz7SG7qy
Copy the code

Continue editing index.ts and add:

/** Query the weather API */
const appid = "your appid";
const appsecret = "your appsecret";

let url = `https://tianqiapi.com/api?version=v1&appid=${appid}&appsecret=${appsecret}`;
if (isCitySeted) {
  url += `&city=${city}`;
}

const res = await fetch(url);
const weatherObj = await res.json();
Copy the code

Explanation:

  • The APPID you applied for
  • The APPSecret you applied for
  • Url address of the composite interface
  • Check whether the specified city parameter needs to be added
  • The request returns a response object
  • Gets the JSON object in the response body

Run to retrieve weather data.

Output formatting results

Once the data is retrieved, the output can be parsed and formatted.

Response Parameter Description

Parameter Type Description Remarks cityID String City ID update_time String Update time of the observatory City String City name cityEn String City name Country String Country name CountryEn String Data String Daily data list 1-7, a total of 7 groups of l WEA String WEATHER IDENTIFIER fixed 9 types of support (you can also use the WEA field yourself): Xue, LEI, Shachen, Wu, Bingbao, yun, Yu, Yin, QING L TEM String Real-Time temperature L TEM1 String high temperature L TEM2 String low temperature L WIN String wind L Win_speed String L Humidity String L air String L air quality L AIR_level String L AIR_TIPS String L air quality descriptionCopy the code

Continue editing index.ts and add:

/** Displays the query result */
console.log(` 【${weatherObj.city}Weather forecast for seven days);

weatherObj.data.forEach((d: any, i: any) = > {
  console.log("-- -- -- -- -- -- -- --");

  console.log("Date:", d.day);
  console.log("Weather:", d.wea);
  console.log("Temperature range:" + d.tem2 + ` ~ ` + d.tem1);
  console.log(Wind direction:, d.win[0] == d.win[1]? d.win[0] : d.win.join("Turn"));
  console.log("Wind level", d.win_speed);
  if (i === 0) {
    console.log("Real-time temperature:", d.tem);
    console.log("Real-time humidity:", d.humidity);
    console.log(Air Quality:, d.air);
    console.log(Air Quality Grade:, d.air_level);
    console.log("Air Quality Description:", d.air_tips); }});Copy the code

Explanation:

  • Output the name of the city in the returned weather information
  • Run through the 7-day forecast data and output the corresponding weather information in sequence. Note that the real-time temperature, humidity and air quality information is available only on the current day.

Create a terminal in this folder and run it

Deno run --allow-net index.ts --city HangzhouCopy the code

Parameters:

  • – allow – net: namely--allow-net trueTo enable the network request permission
  • Hangzhou: The name of the designated city is Hangzhou

Output:

Check file:///xxx/index.ts designated city: hangzhou [hangzhou] seven-day weather forecast -------- date: 27th (today) weather: heavy rain to moderate rain temperature range: 25℃ ~ 33℃ wind direction: North wind Wind level 4-5 to 3-4 Real-time temperature: 31℃ real-time humidity: 48 Air quality: 53 Air quality Level: good air quality Description: The air is good, can go out activities, in addition to a very small number of people who are particularly sensitive to pollutants, no harm to the public! -------- Date: 28th (tomorrow) Weather: light to moderate rain to overcast Temperature range: 22℃ to 26℃ Wind direction: northwest wind to no sustained direction Wind scale 4-5 to <3 -------- Date: 29th (the day after tomorrow) Weather: overcast Temperature range: Wind direction: no sustained wind Direction 24℃ to 31℃ Wind Scale < Force 3 -------- Date: 30th (Sunday) Weather: light rain to clear Temperature range: 26℃ to 32℃ Wind Direction: No sustained wind scale < force 3 -------- Date: 31st (Monday) Weather: Light rain temperature range: 25℃ to 32℃ Wind direction: Ne to nw wind scale 3-4 to 4-5 -------- Date: 1st (Tuesday) Weather: Light rain Temperature range: 26℃ to 31℃ Wind Direction: Northwest wind Wind scale 6-7 to 4-5 -------- Date: 2nd (Wednesday) Weather: light rain to clear Temperature range: 22℃ to 32℃ Wind direction: northwest wind to no sustained wind scale 4-5 to <3Copy the code

conclusion

From my personal experience, Deno has its own characteristics in use. In addition to permission control, there are also some advantages and disadvantages, such as:

advantages

  • Directly into the network library
  • Run directly without manually compiling ts first

disadvantages

  • Some type declaration files, such as Deno itself, are missing
  • The need for async will cause IDE syntax errors that conflict with regular syntax

Of course, the traditional NodeJS command-line tool can use the commander. Js library, can directly package a command line weather forecast program, interested children can try their own.

Weather-app = weather-app = weather-app = weather-app = weather-app

Refer to the article

  1. Use Deno to build a command line weather forecast program – Nuggets