Skip to content

Instantly share code, notes, and snippets.

@pjchender
Last active April 13, 2017 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjchender/0b8af193f91e204bb6618144b207cfaa to your computer and use it in GitHub Desktop.
Save pjchender/0b8af193f91e204bb6618144b207cfaa to your computer and use it in GitHub Desktop.
Create a Command Line Weather Application @ Treehouse
{
"key": "<apikey>"
}
const weather = require('./weather')
// 將所有的參數(陣列)以底線合併成字串,並將所有的空格用底線取代
const query = process.argv.slice(2).join('_').replace(' ', '_')
weather.get(query)
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
@pjchender
Copy link
Author

pjchender commented Apr 3, 2017

[NodeJS 取得 get 資料]

  • 使用 https method 送出 GET request https.get('[path]', callback<res>)
  • 取的 HTTP Status res.StatusCode
  • 開始處理 get request 資料 res.on('data', callback<chunk>)
  • 處理 get request 資料結束 res.on('end', callback)
const request = https.get('[JSON file]', res => {
  //  確認讀取資料為 OK
  if (res.StatusCode === '200') {
    let body = ''
    res.on('data', chunk => {
       body += chunk          // 把資料組回來
    })    //  接收讀到的資料
    res.on('end', () => {/*...*/} )            //  讀取完資料後
  }
}

@pjchender
Copy link
Author

pjchender commented Apr 3, 2017

[處理錯誤訊息]

  • 透過 try {...} catch(error) {...} ,錯誤訊息為 error.message
  • 透過 new Error('自己寫 Error Message.')
//  Print out error message
function printError (error) {
  console.error(error.message)
}

response.on('end', () => {
    try {
        //  parse data
    } catch (error) {
        //  Parse Error
        printError(error)
    }
})

@pjchender
Copy link
Author

[載入與輸出模組]

載入模組

  • 可以寫 require('./profile'),但不可寫 require(profile.js),'./' 不可省略
// 載入模組
const profile = require('./profile.js')
// 使用模組
profile.get

輸出模組

module.exports.get = get

[取得 CMD 中使用者輸入的參數]

  • process 這個物件就像瀏覽器裡的 Window
  • 透過 process.argv 我們可以取得 cmd 中 node 後所輸入的參數
  • 如此我們可以在 cmd 中輸入 node pojungchen chalkers alenaholligan 一樣可以執行
const users = process.argv.slice(2)  // 在 process.argv 中,前兩個是我們不需要的參數
//  將所有的參數(陣列)以底線合併成字串,並將所有的空格用底線取代
const query = process.argv.slice(2).join('_').replace(' ', '_')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment