node.jsのFeedParserライブラリを使ってみる

node.jsでRSSを取得したかったので試しに使ってみる

インストール

パッケージのインストール

npm install feedparser

ソースコード

readable stream でRSSjsonを取得できる http://nodejs.org/api/stream.html#stream_class_stream_readable

feed.js

// feedparser - https://www.npmjs.org/package/feedparser
var FeedParser = require('feedparser')
    , request = require('request');

var req = request('http://b.hatena.ne.jp/entrylist?sort=hot&mode=rss')
    , feedparser = new FeedParser(); // new FeedParser([options])でoptions設定

req.on('error', function (error) {
    // リクエストエラー処理
});
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) {
    // 通常のエラー処理
});
feedparser.on('readable', function() {
    // 処理ロジックを書く
    // metaプロパティはfeedeparserインスタンスのコンテキストに常に置き換える
    var stream = this
        , meta = this.meta
        , item;
    while (item = stream.read()) {
        console.log(item);
    }
});

実行

はてなブックマークのホットエントリーのRSSをリクエストURLとして実行

$ node feed.js
{ title: '詐欺容疑:独身装い末期がん女性に接近、276万円奪う - 毎日新聞',
  description: '<blockquote cite="http://mainichi.jp/select/news/20140909k0000m040104000c.html" title=
・・・
     'rdf:description': { '@': {}, '#': '新着エントリー' },
     'rdf:items': { '@': {}, seq: [Object] } } }

取得できた。

タイトルやリンクが欲しい時は、

feedparser.on('readable', function() {
    var stream = this
        , meta = this.meta
        , item;
    while (item = stream.read()) {
        // タイトルとリンクを取得
        console.log(item.title + "\t" + item.link);
    }
});

として実行すると、

$ node feed.js
OM-D E-M5と単焦点レンズで撮る中秋の名月(のイベント) - Hirolog@茨城    http://www.hirolog-ibaraki.net/entry/moon
豪が潜水艦購入間近か―日本、戦後初の武器輸出に - WSJ http://jp.wsj.com/news/articles/SB10001424052970204707704580141643283765392
卵を割らずにそのまま2分間攪拌することでプリンができる「おかしなたまご まわしてまわしてまるごとプリン」を使ってみました - GIGAZINE http://gigazine.net/news/20140908-egg-pudding/
「iWatch」Appleのウェアラブルデバイスの噂まとめ - マガデジブログ   http://www.magadigi.com/2014/09/iwatch-apple-uwasa.html
詐欺容疑:独身装い末期がん女性に接近、276万円奪う - 毎日新聞 http://mainichi.jp/select/news/20140909k0000m040104000c.html
・・・

簡単!!

その他取得できるプロパティ一覧

  • title

  • description

  • link

  • xmlurl

  • date

  • pubdate

  • author

  • language

  • image

  • favicon

  • copyright

  • generator

  • categories

参考

feedparser https://www.npmjs.org/package/feedparser

Github サンプルコード (danmactough/node-feedparser) https://github.com/danmactough/node-feedparser/tree/master/examples