Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions web/weather-api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
node_modules/
75 changes: 75 additions & 0 deletions web/weather-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# 🌦 Weather CLI App

A simple Node.js command-line application that fetches and displays real-time weather data using the [OpenWeatherMap API](https://openweathermap.org/api).

---

## 📋 Features

- Fetches live weather for any city
- Displays temperature, weather condition, humidity, and wind speed
- Handles errors (invalid city, bad API key, network issues)
- Uses environment variables to protect your API key
- Built with async/await — no callbacks

---

## 🖥 Usage

```bash
node index.js <city>
```

**Examples:**

```bash
node index.js London
node index.js "New York"
node index.js Tokyo
```

**Sample output:**

```

🌍 London, GB

🌡 Temperature : 18°C (feels like 16°C)
🌤 Weather : Clear sky
💧 Humidity : 60%
💨 Wind Speed : 3.5 m/s
```

---

## ⚠️ Error Handling

| Scenario | Message |
| ----------------- | -------------------------------------------------------------------- |
| No city provided | `Usage: node index.js <city>` |
| Invalid city name | `City "example" not found. Please check the city name.` |
| Invalid API key | `Invalid API key. Please check your OPENWEATHER_API_KEY.` |
| Network failure | `Network error: Unable to reach the weather API.` |
| Missing API key | `Missing API key. Please set OPENWEATHER_API_KEY in your .env file.` |

---

## 📁 Project Structure

```
weather-cli/
├── index.js # Main application logic
├── .env # The API key (hadi lazm tpushiha XD)
├── package.json # Project metadata and dependencies
└── README.md # This file
```

---

## 📦 Dependencies

| Package | Purpose |
| -------- | --------------------------------------- |
| `dotenv` | Loads environment variables from `.env` |
| | |

71 changes: 71 additions & 0 deletions web/weather-api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import "dotenv/config";

const API_KEY = process.env.OPENWEATHER_API_KEY;
const BASE_URL = "https://api.openweathermap.org/data/2.5/weather";

async function getWeather(city) {
if (!API_KEY) {
throw new Error(
"Missing API key."
);
}

const url = `${BASE_URL}?q=${encodeURIComponent(city)}&appid=${API_KEY}&units=metric`;

const response = await fetch(url);
const data = await response.json();

if (!response.ok) {
if (response.status === 401) {
throw new Error("Invalid API key. Please check your OPENWEATHER_API_KEY."); // 401 Unauthorized when the API key is invalid or missing
}
if (response.status === 404) { // 404 Not Found when the city does not exist
throw new Error(`City "${city}" not found. Please check the city name.`);
}
throw new Error(`API error (${response.status}): ${data.message}`); // Handle other errors like 500...ect
}

return data;
}

function displayWeather(data) {
const city = data.name;
const country = data.sys.country;
const temp = Math.round(data.main.temp);
const feelsLike = Math.round(data.main.feels_like);
const description =
data.weather[0].description.charAt(0).toUpperCase() +
data.weather[0].description.slice(1);
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;

console.log(` 🌍 ${city}, ${country} \n`);
console.log(` 🌡 Temperature : ${temp}°C (feels like ${feelsLike}°C)`);
console.log(` 🌤 Weather : ${description}`);
console.log(` 💧 Humidity : ${humidity}%`);
console.log(` 💨 Wind Speed : ${windSpeed} m/s`);
}

async function main() {
const city = process.argv[2];

if (!city) {
console.error("Usage: node index.js <city>");
console.error("Example: node index.js London");
process.exit(1);
}

try {
const data = await getWeather(city);
displayWeather(data);
} catch (error) {
if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
console.error("Network error: Unable to reach the weather API. Check your internet connection.");
} else {
console.error("Something went wrong:", error.message);
}
process.exit(1);
}
}

main();
120 changes: 120 additions & 0 deletions web/weather-api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions web/weather-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "weather-cli",
"version": "1.0.0",
"description": "A Node.js CLI app that fetches and displays weather data.",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js"
},
"keywords": [
"weather",
"cli",
"openweathermap",
"nodejs"
],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"node-fetch": "^3.3.2"
}
}