我正在设置一个订阅RSS提要的node.js服务器。当有新项目发布到提要时,我希望服务器解析该信息并将其传递给API,以警告最终用户。我可以使用feedparser作为订户吗?
我了解到该库创建了一个EventEmitter来触发动作。是否可以导出此功能并使其与Express应用程序并行运行?
来自解析器示例:
const FeedParser = require('feedparser')
const request = require('request')
const subscriber = async () => {
const req = request('https://www.reddit.com/.rss')
const feedparser = new FeedParser()
req.on('error', (error) => {
console.log(error)
})
req.on('response', (r) => {
const stream = this
if (r.statusCode !== 200) {
this.emit('error', new Error('bad status code'))
} else {
stream.pipe(feedparser)
}
})
feedparser.on('readable', () => {
// This is where the action is!
const stream = this
var item = ''
while (item = stream.read()) {
console.log(item)
}
})
return feedparser
}
module.exports = {
subscriber
}
当我调用此函数时,我希望控制台记录新项目,但没有任何项目。原因尚不清楚。
奖金问题:我是否可以在无需等待新项目发布的情况下验证订阅是否正常运行?是否存在可以模拟该行为的RSS工具或网站?
答案 0 :(得分:3)
我学到的东西:
var app = require('../app');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Start the subscriber
*/
var feed = new RssFeed({your rss feed url}, 60000); // 60000 = 60 second refresh rate
feed.start();
还包括我的实现的不完整代码段:
const Parser = require('rss-parser')
class RssSubscriber extends Parser {
constructor (url, interval) {
super()
this.url = url
this.interval = interval
this.latestPublishTime = null
}
start () {
// execute on an interval
setInterval(async () => {
try {
console.log('Fetching feed...')
const news = await this.parseFeed()
await Promise.all(news.map(n => { return this.alert(n) }))
} catch (err) {
console.log('WARN: Error Encountered when fetching subscription items.')
}
}, this.interval)
}