我正在尝试将RSS feed中的每个项目保存到一个JSON文件中,以便稍后读取,并且我正在使用feedparser。当我尝试将每个项目推送到要另存为JSON的对象时,我正在逐步覆盖最后一个项目。我尝试将writeFeed()
函数移出feedparser.on()
范围,但这会使feed数据未声明。处理我丢失的feedparser流是否有其他区别,还是我忽略了有关循环的明显内容?
let req = request('https://travel.state.gov/_res/rss/TAsTWs.xml')
const feedparser = new FeedParser();
req.on('error', function (error) {
// handle request errors
});
req.on('response', function (res) {
var stream = this; // `this` is `req`, which is a stream
if (res.statusCode !== 200) {
this.emit('error', new Error('Bad status code'));
}
else {
stream.pipe(feedparser);
}
});
feedparser.on('error', function (error) {
// handle errors
});
feedparser.on('readable', function () {
var stream = this; // `this` is `feedparser`, which is a stream
var meta = this.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance
var item;
let feed = [];
while (item = stream.read()) {
feed.push({title: item.title});
}
let jsonFeed = JSON.stringify(feed);
function writeFeed(data) {
fs.writeFile('savedFeed.json', JSON.stringify(data), 'utf8', function(error) {
if(error) {
console.log('error: ' + err);
} else {
console.log('report: success');
}
});
}
writeFeed(jsonFeed);
});