Created
September 21, 2017 08:32
-
-
Save yunnysunny/4ae5ce55fe0315b513dfeac7f3a3d15d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment