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

Discover more amazing content handpicked just for you

Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

node etherscanBalance.js

If everything is set up correctly, you’ll see an output like this:

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

Now that the backend is up, let's move to the React frontend.

In the frontend/src/ directory, modify App.js to call the Flask API and display the message:

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

In this example:

Sep 02, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

npm create vite@latest my-react-app -- --template react

Navigate into your project directory:

Aug 14, 2024
Read More
Tutorial
dart

Building an Advanced Weather App with Flutter and Dart

Before we start, ensure that your Flutter environment is set up. You should have Flutter and Dart installed, along with an IDE like Android Studio or Visual Studio Code.

Our weather app will:

Aug 12, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!