Create a Command Line Weather Application @ Treehouse
const http = require('http')
const https = require('https')
const api = require('./api.json')
// Print out temp details
function printWeather (weather) {
const message = `Current temperature in ${weather.location.city} is ${weather.current_observation.temp_c}C`
console.log(message)
}
// Print out error message
function printError (error) {
console.error(error.message)
}
function get (query) {
// 為了閱讀舒適度,把底線拿掉
const readableQuery = query.replace('_', ' ')
// 如果一個錯誤的 URL 傳進來會立即被捕捉
try {
const request = https.get(`https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json`,
response => {
if (response.statusCode === 200) {
let body = ''
// Read the data
response.on('data', chunk => {
body += chunk
})
response.on('end', () => {
try {
// parse data
const weather = JSON.parse(body)
// 列印資料前看看該地點是否存在
if (weather.location) {
// print data
printWeather(weather)
} else {
const queryError = new Error(`The location "${readableQuery}" was not found.`)
printError(queryError)
}
} catch (error) {
// Parse Error
printError(error)
}
})
} else {
// 狀態錯誤(Status Code Error)
const statusCodeError = new Error(`There was an error getting the message for ${readableQuery}. (${http.STATUS_CODES[response.statusCode]})`)
printError(statusCodeError)
}
})
request.on('error', error => {
printError(error)
})
} catch (error) {
// 錯誤的 URL 格式
printError(error)
}
}
module.exports.get = get
const weather = require('./weather')
// 將所有的參數(陣列)以底線合併成字串,並將所有的空格用底線取代
const query = process.argv.slice(2).join('_').replace(' ', '_')
weather.get(query)
{
"key": "<apikey>"
}