Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@atufkas
Last active August 26, 2021 22:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save atufkas/3917709 to your computer and use it in GitHub Desktop.
Save atufkas/3917709 to your computer and use it in GitHub Desktop.
rss feed generation from mongojs result using node, express and node-rss

Situation

For my tiny blog (engine) based on node, express/connect and mongojs I needed a simple rss feed solution. I discovered and decided to go with the nice working npm module node-rss instead of writing xml myself.

What this code example does

Basically I create an get event on route /feed/rss, generate a node-rss object initialized with base values and add item elements to it while looping over a mongojs collection result array (holding my post items to be reflected). Finally I send a response with an appropriate content type header. My example is directly bound to an express get event callback for a simple static request path, but you may of course move it to route exports or whatever.

Notes

No big deal, but you might find this portion of code useful as a starting point when seeking for rss solutions.

...
// Require nm module "rss" (node-rss)
var rss = require('rss');
...
// My mongojs connect() object is assigned to app.db
app.db = mongojs.connect('myblog');
...
// Express get listener event for url to RSS feed
app.get('/feed/rss', function(req, res) {
// Create rss prototype object and set some base values
var feed = new rss({
title: 'John Does Blog',
description: 'about me and my foo and my bar',
feed_url: 'http://' + req.headers.host + req.url,
site_url: 'http://' + req.headers.host,
image_url: 'http://' + req.headers.host + '/images/icon.png',
author: 'John Doe'
});
// Fetch 10 published posts from data store (mongodb in my case)
// sorted by creation date.
app.db.collection('post').find({
state: 'published'
}).limit(10).sort({
created: -1
}, function(err, posts) {
if (! err && posts) {
posts.forEach(function(item,post) {
// Fields are stored straight forward within my mongodb
// collection. Just as a note: The blog style permalink
// is created with "urlifying" the subject on creation time
// and adding date fragments with momentjs
feed.item({
title: post.subject,
description: post.summary,
url: 'http://' + req.headers.host + post.permalink_path,
author: post.author.username,
date: post.created
});
});
// Set content type header and send xml response.
// Note: res.type() uses mimetype definition as a base.
// As an alternative you may explicitly use res.set():
// res.set('Content-Type', 'application/rss+xml');
res.type('rss');
res.send(feed.xml());
}
});
});
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment