w.png
/**
* 实现串行化流程控制
*
*/
const fs = require('fs')
const request = require('request')
const htmlparser = require('htmlparser')
const configFileName = './rss_feeds.txt'
//检查文件是否存在,确保文件没问题.
function checkForRSSFile(){
fs.exists(configFileName,(err,exist)=>{
if(!exist){
return next(new Error(`missing RSS file ${configFileName}`))
}
next(null,configFileName)
})
}
//读取文件内容
function readRSSFile(configFileName){
fs.readFile(configFileName,(err,feedList)=>{
if(err){
next(err)
return
}
feedList = feedList.toString()
.replace(/^\s+|\s+$/g,'')
.split('\n')
let random = Math.floor(Math.random() * feedList.length)
next(null,feedList[random])
})
}
function downloadRSSFeed(feedUrl){
request({url:feedUrl},(err,response,body) =>{
if(err) next(err)
if(response.statusCode != 200){
return next(new Error('abnormal response status code.'))
}
next(null,body)
})
}
var tasts = [
checkForRSSFile,
readRSSFile,
downloadRSSFeed
]
function next(err,result){
if(err) throw err //往上抛出异常
let currentTask = tasts.shift() //返回数组一个元素,并且删除
if(currentTask){ //如果判断函数存在
currentTask(result) //执行函数
}
}
next() //开始执行当前任务
网友评论