Published on August 08, 2024By DeveloperBreeze

Weather App with Node.js

First, ensure you have Node.js installed on your system. You will also need an API key from [OpenWeatherMap](https://openweathermap.org/api).

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.

This simple weather app demonstrates how to make HTTP requests in Node.js, handle asynchronous operations, and interact with a third-party API, making it an excellent example for developers interested in building command-line tools or exploring Node.js capabilities.

Comments

Please log in to leave a comment.

Continue Reading:

Fetching Address Details from Solana

Published on August 09, 2024

javascriptjson

Tracking Newly Created Tokens on Ethereum

Published on August 09, 2024

javascriptnodejs

Tracking Newly Created Tokens on Solana

Published on August 09, 2024

javascriptnodejs

Tracking Solana Address for New Trades and Amounts

Published on August 09, 2024

javascriptnodejs

Node.js: How to Create an HTTP Server

Published on August 12, 2024

javascriptnodejs

GraphQL API Server with Node.js and Apollo Server

Published on August 12, 2024

nodejsgraphql

Building a GraphQL API with Node.js and Apollo Server

Published on August 12, 2024

javascriptnodejsgraphql

Building a React Application with Vite and Tailwind CSS

Published on August 14, 2024

javascriptnodejs