First, let's make the directory. The directory will be called weather. And in the weather directory we'll make a new file called weather.js.
Now in this file we can take all of our code from app.js, and paste it in weather.js:
const request = require('request');
request({
url: 'https://api.forecast.io/forecast/4a04d1c42fd9d32c97a2c291a32d5e2d/39.9396284,-75.18663959999999',
json: true
}, (error, response, body) => {
if (error) {
console.log('Unable to connect to Forecast.io server.');
} else if (response.statusCode === 400) {
console.log('Unable to fetch weather.');
} else if (response.statusCode === 200) {
console.log(body.currently.temperature);
}
});
The only thing we need to do in order to take this code and convert it to create that function, which will get exported. And then we can move our call to the request inside of it. We'll make a brand new function called getWeather next to the request variable:
const request = require('request');
var getWeather = () => {
};
getWeather will take some arguments, but that'll be added later. For now we'll leave the arguments list empty. Next, we'll take our call to request and move it inside the getWeather function:
const request = require('request');
var getWeather = () => {
request({
url: 'https://api.forecast.io/forecast/4a04d1c42fd9d32c97a2c291a32d5e2d/39.9396284,-75.18663959999999',
json: true
}, (error, response, body) => {
if (error) {
console.log('Unable to connect to Forecast.io server.');
} else if (response.statusCode === 400) {
console.log('Unable to fetch weather.');
} else if (response.statusCode === 200) {
console.log(body.currently.temperature);
}
});
};
Then, we can go ahead and export this getWeather function. We'll add module.exports.getWeather and set it equal to the getWeather function that we defined up:
module.exports.getWeather = getWeather;