Skip to content

Instantly share code, notes, and snippets.

@yunnysunny
Created September 21, 2017 08:32
Show Gist options
  • Select an option

  • Save yunnysunny/4ae5ce55fe0315b513dfeac7f3a3d15d to your computer and use it in GitHub Desktop.

Select an option

Save yunnysunny/4ae5ce55fe0315b513dfeac7f3a3d15d to your computer and use it in GitHub Desktop.

Revisions

  1. yunnysunny created this gist Sep 21, 2017.
    45 changes: 45 additions & 0 deletions feed_parse.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    var request = require('request');
    var xml2js = require('xml2js');
    var url = 'http://blog.whyun.com/feed.xml';
    var keyword = '异步';
    function parseResponse(url,description, error,response,body,callback) {
    if (error) {
    console.error('请求'+url+'失败',error);
    callback('请求'+description+'网络错误');
    return;
    }
    if (!response) {
    callback('请求'+description+'失败,未知错误');
    return;
    }
    if (response.statusCode != 200) {
    console.error(url, response.statusCode, body);
    callback('请求'+description+'失败['+response.statusCode+']');
    return;
    }
    xml2js.parseString(body,{explicitRoot:false,explicitArray : false},function(err,data) {
    if (err) {
    console.error('解析返回数据失败',err,body);
    return callback('解析返回数据失败');
    }
    callback(false,data);
    });
    }
    request({
    url:url,
    headers:{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
    },function(error,response,body) {
    parseResponse(url,'解析xml',error,response,body,function(err,data){
    if (err) {
    return;
    }

    if (!data || !data.channel || !data.channel.item) {
    return console.error('数据非法',data);
    }
    var articles = data.channel.item.filter(function(item) {
    return item.title && item.title.indexOf(keyword) !== -1;
    });
    console.log(articles);
    });
    });