Node.js http get page title

Description

Node.js http get page title


var http=require('http'), url=require('url');
var u=url.parse('http://www.java2s.com/');

console.dir(u);/*from  w w w .  jav  a  2 s  .co  m*/

var options = {
  host: u.host,
  port: u.port||80,
  path: u.pathname||'/'
};

console.dir(options);

http.get(options, function(res) {
  var body='', title='';
  res.on('data', function (chunk) {
    body+=chunk;
    if (!title && /<title>.*<\/title>/im.test(body)){
      console.log('data arrived, testing...');
      title=body.match(/<title>(.*)<\/title>/im)[1];
    }
  });
  res.on('end', function(){
    console.log('title: '+unescape(title));
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});



PreviousNext

Related