After completing the [Node.js 101] Getting Started tutorial, we will make a small meteorologic App where the objective will give some specified weather information of a specified chosen region like, temperature and humidity, using Node.js and the OpenWeatherMap API. This last one, as a public API, will allow us to access that specific weather information using a API Key.
[ OpenWeatherMap Account ]
Go to OpenWeatherMap website and login in with your credentials, if you dont have a account yet make one.
After login in, click on the ‘API Keys’ tab where will appear a default key where you can use that one or create a new one. (Note: If you choose to create a new one, remember that will maybe take some time for the new key get available to use).
[ Developing the App ]
As done in the [Node.js 101] Getting Started article, in a Microsoft Windows 7 machine, and in any location desired (for example, Desktop), press SHIFT+RIGHT MOUSE and select “Open Command Window here”.
(For Windows 10 users if not active, that feature can be activated with some additional steps, where in the future will be a article explaining how to do it but for now you can run the command prompt normally and navigating forward using ‘cd [foldername]’ or backwards using ‘cd..’ until you reach the desired location.)
With the Command Prompt Windows let’s create a new folder named nodejs-weather using the following command:
mkdir nodejs-weather
Define the nodejs-weather as the actual path of the Command Prompt Window navigating into it:
cd nodejs-weather
Now we will initialize the project using a command that is a step-by-step tool to scaffold out the project. This command will prompt you for input for a few aspects of the project in the following order:
- The project’s name,
- The project’s initial version,
- The project’s description,
- The project’s entry point (meaning the project’s main file),
- The project’s test command (to trigger testing with something like Standart),
- The project’s git repository (where the project source can be found),
- The project’s keywords (basically, tags related to the project),
- The project’s license (this default to ISC — most open-source Node.js projects are MIT).
For now, for a simplicity way, you can only input a description and the author if you want. To continue, execute the command and when asked input the information and/or press ENTER:
npm init
After confirming the ‘Is this OK? (yes)’ message by pressing ENTER, we will create a index.js file and invoke the OpenWeatherMap API.
[ Invoking the OpenWeatherMap API ]
On the Command Prompt Windows with the same path of the nodejs-weather folder, create a index.js file using the command (Windows):
nul type >> index.js
(Note: if you are following this tutorial as it showed, when creating the index.js file with the command prompt window, the Windows maybe present a small dialog box. Don’t worry about it and press OK).
Now, we will install the npm request module that will allow us to use a URL as argument that with the module will invoke the method of the API and giving back the result. To install the npm request module, execute:
npm install request -save
After this processing it’s done, you will have something similar as:
Now let’s edit the index.js, after executing cls command to clean the command prompt window case you want it, using any text or source code editor, we will put the following code and add it your OpenWeatherMap API Key:
let request = require('request');
let apiKey = '*****************************';
let city = 'Guarda';
let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
console.log('body:', body);
}
});
Save it and in the Command Prompt Window execute:
node index.js
If everything is working until this point, the Command Prompt Window will present a message with a bunch of data related to the weather information specified to the city defined in the code above, but we can edit the code for a clean output message.
[ A Small and Clean Weather Information App ]
With the steps executed above successfully, now we will edit the code in the manner to give us back a clean output since the data is formatted in JSON. Using JSON.parse, for now, we will select the temperature and humidity as the desired fields.
Using the following command, we will defining the JSON output as a JavaScript object:
let weather = JSON.parse(body)
As object, now we can access the desired fields on it, for example, using:
let message = `Temperature for ${weather.name}:
${weather.main.temp}º`;
console.log(message);
To finalize, change the index.js file with the new following code and same API Key:
let request = require('request');
let apiKey = '*****************************';
let city = 'Guarda';
let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
let weather = JSON.parse(body);
let message = `
Weather Information for ${weather.name}:
----------------------------------------
- Temperature: ${weather.main.temp} ºC
- Humidity: ${weather.main.humidity} %`
console.log(message);
}
});
Save it and in the Command Prompt Window execute:
node index.js
Hope you liked this small article, best regards, Ricardo Costa (Richards).
This article was created in a context of the Distributed Systems Class 2020–21, ESTG-IPG.