DeveloperBreeze

Weather App with Node.js

javascript

Step 1: Set Up the Project

Create a new directory for your project and navigate into it:

mkdir weather-app
cd weather-app

Initialize a new Node.js project and install the axios library to handle HTTP requests:

npm init -y
npm install axios

Step 2: Create the Weather App Script

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();
});

Step 3: Run the Weather App

To run the script, execute the following command in your terminal:

node weather.js

Enter a city name when prompted, and the app will fetch and display the current weather for that city.

Explanation

  • Node.js and Axios: The script uses Node.js and the axios library to make HTTP requests to the OpenWeatherMap API.
  • Async/Await: The getWeather function uses async/await syntax to handle asynchronous operations.
  • User Input: The script uses the readline module to prompt the user for a city name.
  • Weather Data: The app fetches the current weather data for the specified city, including temperature, description, and humidity.

Notes

  • API Key: Replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key.
  • Error Handling: The script includes basic error handling to notify the user if the weather data cannot be retrieved.

Continue Reading

Handpicked posts just for you — based on your current read.

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!