Node.js开发入门—使用http访问外部世界

来源:互联网 发布:支付宝注销淘宝账号呢 编辑:程序博客网 时间:2024/06/14 17:10

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
5 0
原创粉丝点击