M
M
Michael2016-11-15 20:34:15
Node.js
Michael, 2016-11-15 20:34:15

How to fix the streaming logic?

I use here this module for work with RSS. I took an example from there, everything works. But my 'readable' event fires many times when sending one request to the site. How can I make it so that the request is sent only once?
Tried to use stream.end(), but didn't work

const req = request('https://tjournal.ru/rss'),
      feedParser = new FeedParser();
req.on('response', function(res) {
  this.pipe(feedParser);
});

feedParser.on('readable', function() {
  var stream = this, item;
  if (item = stream.read()) {
    console.log(item.title, item.link);
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leo Developer, 2016-11-15
@crazy_leo

The event must fire many times, this is how streams work.
If you want to collect everything, and then do some action at the end, then here is an approximate solution:

var FeedParser = require('feedparser')
  , request = require('request');

var req = request('https://tjournal.ru/rss'),
      feedParser = new FeedParser();
req.on('response', function(res) {
  this.pipe(feedParser);
});

var titles = [], emitted = false

feedParser.on('readable', function() {
  var stream = this, item

  if (item = stream.read()) {
    titles.push(item.title)
  }

  !emitted && (emitted = true) && stream.on("end", function () {
    console.log(titles)
  })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question