Node.js開發入門—使用http訪問外部世界,node.js訪問

來源:互聯網
上載者:User

Node.js開發入門—使用http訪問外部世界,node.js訪問

Node.js的http模組,不但可以構建伺服器,也可以作為用戶端類庫來訪問別的伺服器。關鍵就在兩個方法:

  • http.request(options[,callback])
  • http.get(path[,callback])

除了http,還會用到FileSystem模組和Stream中的stream.Readable和stream.Writable。

先來大概介紹一下相關API吧。

API解釋

http.request()方法接受一個options參數,這個參數可以是對象,用來指明你要訪問的網路資源相關的選項,比如hostname、path、port、method等。下面是一個簡單的選項,用來下載“http://images.huxiu.com/article/cover/201509/14/074513891816.jpg”這個檔案:

var options = {  hostname: 'images.huxiu.com',  port: 80,  method: 'GET',  path: '/article/cover/201509/14/074513891816.jpg',  keepAlive: false};

http.request()方法返回一個http.ClientRequest執行個體,調用http.request()後,必須在調之後的某個地方調用一次req.end,類似下面:

var req = http.request(options, function(res){  console.log(res.statusCode);});...req.end();

否則,請求不會發出去哦,你的程式會“呆”在哪裡,茫然不知所措。

而使用http.get()則不用調用req.end(),因為http.get()自動幫我們做了。

我們看到http.request()和http.get()都有一個回調方法,這個回調方法的參數res是http.IncomingMessage的執行個體,一個Readable Stream,我們可以通過它來擷取服務端返回的狀態和資料。

實際上我們也可以不提供回調給http.request()和http.get(),而是通過監聽ClientRequest的response事件來處理服務端反饋。如你所料,response事件需要的回調和http.request()及http.get()完全一樣。代碼類似這樣:

var req = http.request(options);...req.end();req.on('response', function(res){  ...});
下載圖片的小樣本

樣本比較簡單,下載一個圖片並寫入檔案,完成後退出。代碼如下:

var http = require('http');var fs = require('fs');// req is an instance of http.ClientRequestvar req = http.get('http://images.huxiu.com/article/cover/201509/14/074513891816.jpg');/*var options = {  hostname: 'images.huxiu.com',  port: 80,  method: 'GET',  path: '/article/cover/201509/14/074513891816.jpg',  keepAlive: false};var req = http.request(options, function(res){    console.log(res.statusCode);});//req.end() must be called while http.request() is use to issue a requestreq.end();*/req.on('error', function(e){  console.log(e);});var savedStream = null;var savedFd = 0;function endSaved(){  if(savedStream != null){    savedStream.end();  }}//res is an instance of http.incomingMessagereq.on('response', function(res){  console.log('statusCode - ', res.statusCode);  console.log('contentLength - ', res.headers['content-length']);  if(res.statusCode == 200){    savedFd = fs.openSync('test.jpg', 'w');    if(savedFd > -1){      savedStream = fs.createWriteStream('test.jpg', {fd: savedFd});      console.log('write stream created.');      savedStream.on('finish', function(){        console.log('data saved finished.');        process.exit(0);      });    }  }else{    console.log('error occured.');    process.exit(1);  }  res.on('data', function(chunk){    //console.log('got data - ', chunk);    if(savedStream != null){      if(savedStream.write(chunk)){        console.log('data write directly.');           }    }  });  res.on('close', function(){      console.log('res closed, end save now.');      endSaved();  });  res.on('end', function(){    console.log('res end, end save now.');    endSaved();  });  res.on('error',  function(e){    console.log('res err, end save now.');    endSaved();  });});

我使用http.get()方法來下載圖片。也測試了http.request(),注釋起來的代碼就是,開啟它,屏蔽http.get()那行代碼就可以了。

當檔案下載完成時,res(http.IncomingMessage)會發射一個名為“end”的事件,我監聽它來關閉儲存的檔案。

注意我監聽req(http.ClientRequest)的response事件來處理服務端的反饋。開啟檔案時我使用了fs.openSync(),採用同步方式,這樣編程更簡單一些。fs.openSync()返回一個檔案描述符(fd),我把它傳遞給fs.createWriteStream來建立一個fs.WriteStream執行個體,然後使用它來寫檔案。

其它文章:

  • Node.js開發入門——通訊端(socket)編程
  • Node.js開發入門——notepad++ for Node.js
  • Node.js開發入門——使用對話方塊ngDialog
  • Node.js開發入門——引入UIBootstrap
  • Node.js開發入門——用MongoDB改造LoginDemo
  • Node.js開發入門——MongoDB與Mongoose
  • Node.js開發入門——使用cookie保持登入
  • Node.js開發入門——使用AngularJS內建服務
  • Node.js開發入門——Angular簡單樣本
  • Node.js開發入門——使用AngularJS
  • Node.js開發入門——使用jade模板引擎
  • Node.js開發入門——Express裡的路由和中介軟體
  • Node.js開發入門——Express安裝與使用
  • Node.js開發入門——HTTP檔案伺服器
  • Node.js開發入門——HelloWorld再分析
  • Node.js開發入門——環境搭建與HelloWorld

著作權聲明:本文為foruok原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.