我正在尝试在node.js 中实现小型RSS 阅读器(它将提要数据呈现为html 页面)。
到目前为止我已经做到了这一点:
var FeedParser = require(__dirname + '/../node_modules/feedparser')
, request = require(__dirname + '/../node_modules/request');
exports.news = function(req, res){
var news = [];
request('http://feeds.feedburner.com/niebezpiecznik/')
.pipe(new FeedParser())
.on('error', function(error) {
// ...
})
.on('meta', function (meta) {
console.log('===== %s =====', meta.title);
console.log('**** %s ****', meta.description);
console.log();
})
.on('readable', function() {
var stream = this, item;
var i = 0;
while (item = stream.read()) {
var this_news = {
'title': item.title,
'description': item.description
}
news.push(this_news);
console.log(i++);
}
res.render('rss', {
title: 'Node.js based RSS reader',
newsi: JSON.stringify(news)
});
});
};
带有以下 Jade 模板:
扩展布局
block content
h1= title
p Welcome to #{title}
script(type='text/javascript').
var inews = JSON.parse('!{newsi}');
console.log(inews);
ul
for news in newsi
li= news
else
li sorry, no newsHERE!
但我不断收到以下错误:
0
GET /rss 304 532ms
0
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.res.setHeader (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/node_modules/connect/lib/patch.js:63:22)
at ServerResponse.res.set.res.header (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/response.js:527:10)
at ServerResponse.res.contentType.res.type (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/response.js:396:15)
at ServerResponse.res.send (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/response.js:112:14)
at fn (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/response.js:794:10)
at View.exports.renderFile [as engine] (/home/XXX/programming/nodejs/node-express-aws/node_modules/jade/lib/jade.js:222:12)
at View.render (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/view.js:76:8)
at Function.app.render (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/application.js:504:10)
at ServerResponse.res.render (/home/XXX/programming/nodejs/node-express-aws/node_modules/express/lib/response.js:798:7)
我应该把这个render
部分放在哪里?
我认为,即使您从其处理程序中调用 read
,read
事件也可能会被多次触发。
我不熟悉 Feedparser 模块,但请尝试使用 data
和 end
事件:
.on('data', function(item) {
var this_news = {
'title': item.title,
'description': item.description
}
news.push(this_news);
console.log(i++);
})
.on('end', function() {
res.render('rss', {
title: 'Node.js based RSS reader',
newsi: JSON.stringify(news)
});
});
如果这不起作用,您仍然可以使用 read
事件处理程序,但请确保从 end
调用 res.render
处理程序。
我是一名优秀的程序员,十分优秀!