DeveloperBreeze

Javascript Programming Tutorials, Guides & Best Practices

Explore 93+ expertly crafted javascript tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Weather App with Node.js

Code August 08, 2024
javascript

Create a new file named weather.js and add the following code:

const axios = require('axios');

// Replace with your own OpenWeatherMap API key
const apiKey = 'YOUR_API_KEY';

// Function to get the weather for a city
async function getWeather(city) {
    try {
        const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather`, {
            params: {
                q: city,
                appid: apiKey,
                units: 'metric'
            }
        });

        const weather = response.data;
        const temperature = weather.main.temp;
        const description = weather.weather[0].description;
        const humidity = weather.main.humidity;

        console.log(`Weather in ${city}:`);
        console.log(`Temperature: ${temperature}°C`);
        console.log(`Description: ${description}`);
        console.log(`Humidity: ${humidity}%`);
    } catch (error) {
        console.error(`Could not retrieve weather data: ${error}`);
    }
}

// Prompt the user for a city name
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

readline.question('Enter the city name: ', city => {
    getWeather(city);
    readline.close();
});