Front2End
  • Introduction
  • Front
    • Introduction
    • 新手入門
    • 相關連結
    • Css
    • Javascript
    • 立即函式
    • Google SpreadSheet 當資料庫
    • 資料視覺化
    • 新年快樂
    • Google御用網頁語言 Node.js
    • 世大運網頁遊戲腳本
    • YDNJS-1.Up&Going
    • YDNJS
    • 新手入門
  • 實做
    • 程式碼片段蒐集
    • 爬蟲
    • 實做: 貪吃蛇
    • 練習: z=ax+by
    • 實做: 爬八卦版的文章
    • LearnYouNode
      • 3 - 同步 IO 讀寫
      • 4 – My First Async I\/O
      • 5 - filter
      • 6 - Make it Modular
      • 7-Http Client
    • road_to_bookdown
    • FreeCodeCamp
  • End
    • node.js
Powered by GitBook
On this page
  • 官網的答案
  • 別人的改良版本

Was this helpful?

  1. 實做
  2. LearnYouNode

7-Http Client

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

官網的答案

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

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

// 發起 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

// 可以讀取 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'

http.get()

Event, emitter.on

Previous6 - Make it ModularNextroad_to_bookdown

Last updated 5 years ago

Was this helpful?

Stream | Node.js v7.2.1 Documentation
HTTP | Node.js v7.2.1 Documentation
Events | Node.js v7.2.1 Documentation
Is the 'on' method in this node.js code a JavaScript method or a node method? - Stack Overflow
javascript - In node.js "request.on" what is it this ".on" - Stack Overflow