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.

Related Posts

More content you might like

Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

  • Replace 'YOUR_ETHERSCAN_API_KEY' with your Etherscan API key.
  • Replace '0xYourEthereumAddress' with the address you want to query.
  • Replace '0xYourTokenContractAddress' with the ERC-20 token's contract address (e.g., USDT or DAI token contract).
  • This script queries the ERC-20 token balance for a specific Ethereum address.
   https://api.etherscan.io/api?module=account&action=txlist&address=0xYourEthereumAddress&startblock=0&endblock=99999999&sort=asc&apikey=YOUR_API_KEY

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

Use create-react-app to set up the React frontend:

npx create-react-app frontend
cd frontend
npm start  # Starts the React development server

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

This tutorial provides a comprehensive introduction to using Axios for making HTTP requests in JavaScript. By understanding these basics, you'll be able to integrate Axios into your applications, streamlining your API interactions and improving your development workflow.

Sep 02, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

Introduction

React's ecosystem is vast, with a multitude of libraries that enhance its functionality and simplify development tasks. This cheatsheet covers a wide array of React libraries, organized by category, with brief descriptions of each. These libraries can help you build robust, maintainable, and efficient React applications.

Aug 21, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!