Node.js二三事

看到一个很赞的演示,搬运一下地址
涉及到http超时处理,stream读写大文件,串并行的异步调用等,对node初学者是很好的启发。
以下是搬运了演示里的一些代码:


var http = require('http');
var parse = require('url').parse;

function urlget(url, callback) {
  var info = parse(url); 
  var options = {host: info.hostname, port: info.port || 80, path: info.path, method: 'GET'};
  var req = null, request_timeout = null;
  request_timeout = setTimeout(function() {
    request_timeout = null; 
    req.abort();
    callback(new Error('Request timeout!!'));
  }, 2000); 
  var req = http.request(options, function(res) {
    clearTimeout(request_timeout);
    var chunks = [], length = 0, response_timeout = null;
    response_timeout = setTimeout(function() { 
      response_timeout = null;
      req.abort();
      callback(new Error('Response timeout!!'));
    }, 2000);
    res.on('data', function(chunk) {
        length += chunk.length;
        chunks.push(chunk);
    }).on('end', function() {
        if(response_timeout) {
          clearTimeout(response_timeout);
          var data = Buffer.concat(chunks,length);
          res.body = data;
          callback(null, res);
        }
    }).on('error', function(err) {
        callback(err, res);
    }).on('aborted', function() {
        if(response_timeout) {
          callback(new Error('Response aborted!!'), res);
        }
    });
  }).on('error', function(err) {
      if(request_timeout) { 
        clearTimeout(request_timeout);
        callback(err);
      } 
  });
  req.end();
};


//验证请求超时
var timeout_url = 'http://t.co/';  
urlget(timeout_url, function(err, res) {
  console.log('getting: ', timeout_url);
  if(err) {
    console.log('error:\n', err, '\nresponse:\n', res ? res.headers : null);
  } else {
    console.log('headers:\n', res.headers, '\nbody:\n', res.body.toString());
  }
});

//正常情况访问
var good_url = 'http://www.baidu.com';
urlget(good_url, function(err, res) {
  console.log('getting: ', good_url);
  if(err) {
    console.log('error:\n', err, '\nresponse:\n', res ? res.headers : null);
  } else {
    console.log('headers:\n', res.headers, '\nbody:\n', res.body.toString());
  }
});

//验证响应超时 自己搭一个服务器 
var res_url = 'http://localhost:1984/foo?s=10'; 
urlget(res_url, function(err, res) {
  console.log('getting: ', good_url);
  if(err) {
    console.log('error:\n', err, '\nresponse:\n', res ? res.headers : null);
  } else {
    console.log('headers:\n', res.headers, '\nbody:\n', res.body.toString());
  }
});

//搭建超时服务器
var http = require('http'), parse = require('url').parse;
http.createServer(function(req, res) {
  var info = parse(req.url, true);
  var s = +info.query.s;
  res.write('Please waitting for ' + s + ' seconds...');
  setTimeout(function() {
    res.end(s + ' seconds, url: ' + req.url);
  }, s * 1000);
}).listen(1984);
console.log('Server http://localhost:1984/');

阅读 1.6k

推荐阅读
orz71
用户专栏

0 人关注
6 篇文章
专栏主页
目录