Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialhan voon wong
11,650 Pointsdoes anyone try openweather and successfully did it ?
does anyone try openweather and successfully did it ?
1 Answer
Justin Kao
5,724 PointsI haven't use Querystring package yet will update later.
getWeather.js
// Require http / https module to GET web data
const http = require('http')
const https = require('https')
const apiKey = require('./apiKey.json')
// Functions
function printWeather (weatherObj) {
let weatherMsg = `
Location: ${weatherObj.name}
Weather: ${weatherObj.weather[0].main}
Temperature: ${Math.round((weatherObj.main.temp-273.15) * 10) / 10}C
`
console.log(weatherMsg);
}
function printErrorMsg (error) {
console.error(error.message);
}
function getWeather (zip, location) {
// weather api
const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zip}&q=${location}&&appid=${apiKey.apiKey}`
try {
const request = https.get(URL, res => {
if (res.statusCode === 200) {
let body = ''
let weatherObj
res.on('data', data => {
body += data.toString()
})
res.on('end', () => {
weatherObj = JSON.parse(body)
printWeather(weatherObj)
})
} else {
const errorCode = new Error(`${location || zip} is not found.(${res.statusMessage}-${res.statusCode})`)
printErrorMsg(errorCode)
}
})
request.on('error', printErrorMsg) // Handle error of connection issue
} catch (error) {
// Handle error of wrong domain issue
printErrorMsg(error)
}
}
module.exports = getWeather
app.js
// Require getWeather module
const getWeather = require('./getWeather')
// Input
const zip = isNaN(process.argv.slice(2)[0]) ? '' : process.argv.slice(2)[0]
const city = zip ? '' : process.argv.slice(2)[0] || ''
const country = zip ? '' : process.argv.slice(2)[1] ? ',' + process.argv.slice(2)[1] : ''
const location = city + country
getWeather(zip, location)