Get current weather data using Node.js

Zápisník experimentátora

Hierarchy: Node.js

In this article, we'll show you how to download online weather data. We will use  openweathermap.org to do this. We will program in javascript. This is the first article in the series that includes Node.js, ESP8266 and Arduino MKR1000. In this article we will explain all the basic information and in other articles we will focus only on programming.

openweathermap.org

This server provides weather data. You can sign up for the server and then get the API key to download weather data from the server and use it for your own purposes. Registration is free of charge if you satisfy with the basic API features. For a list of services, visit openweathermap.org/price.

For our demonstration we will use API functions API Current weather data. For a complete description, visit openweathermap.org/current. We will use two functions.

  • By city name - You call function with a parameter of your city and get weather information.
  • By city ID - You call function with the identifier of your city and get weather information. You get the identifier on the page so you can search for your city and look at the parameter in the URL. For example.

The server returns weather data in JSON format. You can use some parameters to set up some data. For example, you can change the temperature display in Kelvin, Celsius or Fahrenheit. The returned data looks like this.

{ coord: { lon: 19.15, lat: 48.74 },
  weather:
   [ { id: 801,
       main: 'Clouds',
       description: 'few clouds',
       icon: '02n' } ],
  base: 'stations',
  main:
   { temp: 19.43,
     pressure: 1011,
     humidity: 64,
     temp_min: 19,
     temp_max: 20 },
  visibility: 10000,
  wind: { speed: 0.5 },
  clouds: { all: 20 },
  dt: 1525030200,
  sys:
   { type: 1,
     id: 5909,
     message: 0.004,
     country: 'SK',
     sunrise: 1524972341,
     sunset: 1525024594 },
  id: 3061186,
  name: 'Banska Bystrica',
  cod: 200 }

Program for Node.js

The program consists of two files. The first file is the main program. In the second file, there is the class OpenWeatherMap that provides communication with the server. Two things need to be set before use.

  • Install packages using the command npm install.
  • Set up your API key. You can do this directly by editing the source code in the index.js file or by setting it in a system that will be transferred to the program as the variable process.env.APPID. For example, for Windows, use the command set APPID=xxx.

index.js

In this file, the request parameters are set in the variable cfg and the appropriate function is called. First function returns weather data by city name, and the second function returns weather data by city ID.

const OpenWeatherMap = require('./openweathermap.js');

var cfg = {
        APPID: process.env.APPID || 'YOUR_APPID',
        units: "metric"
    };

var api = new OpenWeatherMap(cfg);

///
/// Current weather by city ID (Banska Bystrica)
///
/*api.getCurrentWeatherByCityID('3061186', (err, currentWeather) => {
    if(err) {
        console.log(err.message);
    }
    else {
        console.log(currentWeather);
    }
});*/

///
/// Current weather by city name (Banska Bystrica)
///
api.getCurrentWeatherByCityName('Banska Bystrica', (err, currentWeather) => {
    if(err) {
        console.log(err.message);
    }
    else {
        console.log(currentWeather);
    }
});

openweathermap.js

Class OpenWeatherMap. For retrieving data, it uses the package request to easily build HTTP requests. You can see the API request format directly in the source code.

const request = require("request");

module.exports = class OpenWeatherMap {

    constructor(config) {
        this.config = config;
    }

    getCurrentWeatherByCityName(cityName, callback) {
        var self = this;
        request.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=${this.config.units}&APPID=${this.config.APPID}`,
            (err, data) => {
            self.parseResponse(err, data, callback);
        })
    };

    getCurrentWeatherByCityID(cityId, callback) {
        var self = this;
        request.get(`https://api.openweathermap.org/data/2.5/weather?id=${cityId}&units=${this.config.units}&APPID=${this.config.APPID}`,
            (err, data) => {
            self.parseResponse(err, data, callback);
        })
    };

    parseResponse(err, data, callback){
        var error = null;
        var response = null;
    
        error = err;
        if(data) {
            if(data.statusCode != 200) {
                var e = JSON.parse(data.body)
                error = new Error(e.message);
                error.status = e.cod;
            }
            if(data.body) {
                response = JSON.parse(data.body);
            }
        }
    
        callback(error, response);
    }

} 

Source code

The source code is located on the GitHub server.


30.04.2018


Menu