danmactough / node-feedparser

Robust RSS, Atom, and RDF feed parsing in Node.js
Other
1.97k stars 192 forks source link

global var wouldn't be changed when parsing #282

Open newusername2022 opened 4 years ago

newusername2022 commented 4 years ago

version of FeedParser: feedparser@^2.1.0 version of Node: v12.16.3

Hi I'm making a hexo blog and trying to use npm feedparser to parse some feeds and add to my blog.

I'm struggling with writing js in jsx. It seems to me that the global var blogrolltext wouldn't be changed outside feedparser.on function.

function get_blogrolltext(rssfeed){
    let blogrolltext = "";

    if (rssfeed){
        var FeedParser = require('feedparser');
        var fetch = require('node-fetch'); // for fetching the feed
        var req = fetch(rssfeed);
        var feedparser = new FeedParser();

        req.then(function (res) {
          if (res.status !== 200) {
            throw new Error('Bad status code');
          }
          else {
            // The response `body` -- res.body -- is a stream
            res.body.pipe(feedparser);
          }
        }, function (err) {
            console.log('error request');
          // handle any request errors
        });
        feedparser.on('error', function (error) {
          console.log('error reading rssfeed');// always handle errors
        });

        let n = 2;

        feedparser.on('readable', function () {  // here's the part I wrote

          var item = this.read ();
          if (item !== null) {
            if (n > 0) {
                console.log(item.title); //correct value
                console.log(item.date); //correct value
                console.log(item.link); //correct value
                n -= 1;
                blogrolltext += listItem(item.date, item.link, item.title); // try to add 2 feeds on to blogrolltext 

            }
            };

          console.log("line89 blogrolltext: ", blogrolltext); // has correct value

        });

        console.log("line120 blogrolltext: ", blogrolltext); // undefined
        return blogrolltext;
    }

}
function listItem(date, link, title) {
    return '<li>' + date.toISOString().slice(0, 10) +' <a href="' + link + '">' + title + '</a></li> '
}
Profile.Cacheable = cacheComponent(Profile, 'widget.profile', props => {

...
const blogrolltext_1 = get_blogrolltext(rssfeed); // blogrolltext_1 is un-defined
...
}

I'm very confused why a global var wouldn't be changed in here. Is this a scope issue? But I had wrote similar wordcounting function and it had worked. I'm assuming I'm not understanding the feedparser package. I did notice that the console outputs line120 blogrolltext:(empty string) before line89 blogrolltext:(correct values).