main
1#!/usr/bin/env zx
2
3// Copyright 2021 Google LLC
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// https://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17async function main() {
18 const argv = minimist(process.argv.slice(2), {
19 boolean: ['help'],
20 alias: { h: 'help' },
21 })
22
23 if (argv.help) {
24 echo(`
25${chalk.bold('Usage:')} zx fetch-weather.mjs [city name]
26
27Fetches weather data using wttr.in with a neat two-column colored table format.
28
29${chalk.bold('Examples:')}
30 zx fetch-weather.mjs London
31 ./fetch-weather.mjs "New York"
32`)
33 process.exit(0)
34 }
35
36 const args = argv._.slice(__filename === process.argv[1] ? 0 : 1)
37 const city = args.join(' ')
38
39 if (!city) throw 'No city provided. Use -h for help.'
40
41 const svc_url = 'https://wttr.in'
42
43 const data = await spinner(
44 `📡 Fetching weather for "${city}" from ${svc_url}...`,
45 async () => {
46 try {
47 const res = await fetch(
48 `${svc_url}/${encodeURIComponent(city)}?format=j1`,
49 {
50 signal: AbortSignal.timeout(5000),
51 }
52 )
53 if (!res.ok) throw `API error: ${res.status} ${res.statusText}`
54 return res.json()
55 } catch (err) {
56 if (err.name === 'AbortError') {
57 throw 'Request timed out after 5 seconds.'
58 }
59 throw err
60 }
61 }
62 )
63
64 const area = data.nearest_area[0]
65 const current = data.current_condition[0]
66
67 if (!area || !current) {
68 throw '❌ Missing weather data in API response.'
69 }
70
71 const location = area.areaName[0].value
72 const condition = current.weatherDesc[0].value
73 const temperature = current.temp_C
74 const humidity = current.humidity
75
76 echo(chalk.yellow(`🌤️ Weather in ${location}: ${condition}`))
77 echo(chalk.red(`🌡️ Temperature: ${temperature}°C`))
78 echo(chalk.blue(`💧 Humidity: ${humidity}%`))
79}
80
81await main().then(
82 () => process.exit(0),
83 (err) => {
84 const msg = typeof err === 'string' ? err : err.message
85 echo(chalk.red(`❌ ${msg}`))
86 process.exit(1)
87 }
88)
89
90// Here's how to add this script to your shell as a bash alias. This assumes you have zx installed globally.
91// 1. Save this script as `fetch-weather.mjs`.
92// 2. Add the following line to your .bashrc file, replacing the path with your own:
93// alias weather='zx /full/path/to/fetch-weather.mjs'
94// 3. Then reload your shell using the following command:
95// source ~/.bashrc
96// Now you can use the `weather` command to fetch weather data for any city.
97// Example usage: `weather London`