# 7-Http Client

這程式主要的目標是，要抓網頁的原始碼，也就是 html 檔案下來，顯示到 console or terminal 中。也是一個我不看解答就不知道怎麼開始的題目 ...

## 官網的答案

其實官網的答案我看不太懂，尤其是最後一句話 `.on( 'error', console.error)`。為什麼 js 有這麼多違反直覺的東西啊(倒地)

所以我決定，投機取巧，先看別人的改良版本

```javascript
// 發起 http request 和 response
// 但好像不用建立 server

var http = require('http')

http.get(process.argv[2], function (response) {

    response.setEncoding( 'utf8' )
    response.on( 'data' , console.log  )
    response.on( 'error', console.error)

}).on( 'error', console.error)
```

## 別人的改良版本

他同時可以讀取 http 和 https 協定的網頁，然後字串的部份他用 `data.toString()` 來轉換，取代官方的`response.setEncoding( 'utf8' )`。

老實說，我都看不懂啊 orz

```javascript
// 可以讀取 http 和 https 的網頁

var http = require('http')
var https = require('https')

var url = process.argv[2]
var prefix = url.substring(0,8)

if (prefix === 'https://'){
  https.get(url, function (response) {

    response.setEncoding( 'utf8' )
    response.on( 'data', console.log )

   // response.on('data', function (data) {
   //   console.log(data.toString());
   // })
  })
} else {
  http.get(url, function (response) {
    response.on('data', function (data) {
      console.log(data.toString());
    })
  })
}
```

stream, 'data'

* [Stream | Node.js v7.2.1 Documentation](https://nodejs.org/api/stream.html#stream_event_data)

http.get()

* [HTTP | Node.js v7.2.1 Documentation](https://nodejs.org/api/http.html#http_http_get_options_callback)

Event, emitter.on

* [Events | Node.js v7.2.1 Documentation](https://nodejs.org/api/events.html#events_emitter_on_eventname_listener)
* [Is the 'on' method in this node.js code a JavaScript method or a node method? - Stack Overflow](http://stackoverflow.com/questions/8187507/is-the-on-method-in-this-node-js-code-a-javascript-method-or-a-node-method)
* [javascript - In node.js "request.on" what is it this ".on" - Stack Overflow](http://stackoverflow.com/questions/12892717/in-node-js-request-on-what-is-it-this-on)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ayugioh2003.gitbook.io/front2end/shi-zuo/learnyounode/7-http-client.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
