danmactough / node-feedparser

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

Can I use node-feedparser with front end libraries like React or Vue.js? #257

Closed arifmahmudrana closed 6 years ago

arifmahmudrana commented 6 years ago

First of this is a question not any bug report

I saw a related issue https://github.com/danmactough/node-feedparser/issues/191

My question is how can I use node-feedparser to parse a feed with a front end library like React or Vue.js? Is it possible to use with front end library?

I see usage in https://github.com/danmactough/node-feedparser#usage but most of usage uses Node related API's & event so I am not really clear about this can you help me on this @danmactough

arifmahmudrana commented 6 years ago

Found my answer

found an example from that helped https://github.com/zonbitamago/rss-reader/blob/38eb2ffe3e3a0674498062c97d703c25c386d1c3/src/react/utils/utils.js

Here is my solution I added a file in utils/index.js

import FeedParser from 'feedparser'
import axios from 'axios'
import stringToStream from 'string-to-stream'

export function feedParse (url) {
  const feedparser = new FeedParser()
  return axios({ method: 'get', url: url, timeout: 3000 })
    .then(res => {
      // res.data.pipe(feedparser);
      stringToStream(res.data).pipe(feedparser)
    })
    .then(() => {
      var promise = new Promise((resolve, reject) => {
        const items = []
        feedparser.on('readable', function () {
          const stream = this
          let item
          while ((item = stream.read())) {
            items.push(item)
          }
        })

        feedparser.on('end', () => {
          resolve(items)
        })

        feedparser.on('error', err => {
          reject(err)
        })
      })

      return Promise.all([promise])
        .then(feed => {
          return feed[0]
        })
        .catch(err => {
          throw err
        })
    })
    .catch(e => {
      throw new Error()
    })
}

and in my component in created hook I run this

    feedParse(this.rss.url)
      .then(items => {
        this.loading = false
        this.items = items
      })
      .catch(errors => {
        console.log(errors)
      })

N.B: to fetch using axios response header should include CORS