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

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

To delete tasks, update App.js with a delete button for each task:

const deleteTask = (id) => {
  axios.delete(`http://127.0.0.1:5000/tasks/${id}`)
    .then(() => {
      setTasks(tasks.filter(task => task.id !== id));
    })
    .catch(error => console.log(error));
};

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' }
});

apiClient.get('/posts/1')
  .then(response => {
    console.log('Post:', response.data);
  });
  • We create an Axios instance with a base URL and custom configuration.
  • The instance can be reused for multiple requests, simplifying your code.

Sep 02, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

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.

This cheatsheet offers a broad overview of the most widely-used libraries in the React ecosystem. These libraries cover various aspects of React development, from state management and UI components to testing and animations, helping you build robust and maintainable applications. Whether you're a beginner or an experienced developer, integrating these tools into your workflow can significantly enhance your productivity and the quality of your React projects.

Aug 21, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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