()
| 15 | // limitations under the License. |
| 16 | |
| 17 | async 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 | |
| 27 | Fetches 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 |
no test coverage detected
searching dependent graphs…