JavaScript Node.js Basics Create a Command Line Weather Application Project Overview

Peter Retvari
Peter Retvari
Full Stack JavaScript Techdegree Student 8,391 Points

My solution with OpenWeathermap to get LIVE, CURRENT Weather data. 🌩😎☃❅

Hi folks, I'm happy to share my code with you. The hardest part was to set up the API with my API key, I got in a separated email because in the API documentation you only get samples, not current weather data. So if you have the email after a couple of hours of the registration process, you can use the code under Example of API call:

Example of API call

api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=8af2aa7fa978da0c3dc608a85406875c

Here if you don't want to use the country, just delete it with the comma. I didn't want to waste my time to solve it to the country ID as well, so my code works only when you type node app.js and after as many cities as you want. And ofc I'm not done with the error handling part 🙈.

// Problem: get the weather data with numbers or city names by typing in the console and print out the results

// Solution: use the OpenWeather API key to get the data and display it

// Function to get the HTTPS module

const https = require('https');

// Function tp print message to the console

function printMessage(city, temp){
  const message = `In ${city} the current temperature is ${temp} Celsius`;
  console.log(message);
}

// Function to convert Farenheit to celsius
// Celsius = Kelvin - 273.15

function getCelsius (kelvin){
  const celsius = kelvin - 273.15;
  return Math.round(celsius);
}

// Connect to the OpenWeather API and get the raw data
// Example of calls: api.openweathermap.org/data/2.5/weather?q=London,uk

function getTemp (city) {
    const request = https.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=8af2aa7fa978da0c3dc608a85406875c`, response => {
      let body = '';
      // Read the data
      response.on('data', data => {
        body += data.toString();

      }); //data reads ends
      // Parse it 

      response.on('end', data => {
      const weather = JSON.parse(body);
      printMessage(city, getCelsius(weather.main.temp));

      }); // parse ends

    }); //request ends  


} // getTemp funciton ends

// Print out data to the console

// Make it flexible with ARGV key

const getCityTemp = process.argv.slice(2);
getCityTemp.forEach(getTemp);

Hope it will help for some student to don't mess around with the API key