【发布时间】:2014-12-16 01:32:18
【问题描述】:
我正在使用特定的 npm 模块获取提要,我想做的是使用相同的代码创建多个操作,尽管我不想重复整个代码。这是我的控制器:
module.exports = {
buzzy: function (req, res) {
var FeedParser = require('feedparser'),
request = require('request');
var req = request('http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml'),
feedparser = new FeedParser();
req.on('error', function (error) {
// handle any request errors
});
req.on('response', function (res) {
var stream = this;
if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));
stream.pipe(feedparser);
});
feedparser.on('error', function (error) {
// always handle errors
});
feedparser.on('readable', function () {
// This is where the action is!
var stream = this,
meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance
,
item;
while (item = stream.read()) {
var newData = item;
Buzzfeed.create({'title': newData.title, 'url': newData.link, 'source': 'nytimesTech', 'category': 'tech'}, function (err, newTitles) {
});
}
});
}
};
与“嗡嗡”控制器动作非常相似,我想创建多个动作 - 以下是每个控制器中唯一的行
var req = request('http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml'),
和
Buzzfeed.create({'title': newData.title, 'url': newData.link, 'source': 'nytimesTech', 'category': 'tech'}, function (err, newTitles) {
});
很好奇,实现这一点的最佳方法是什么,所以我不再重复了?
【问题讨论】:
标签: node.js model-view-controller sails.js