[译]用Node.js来生成你的内容聚合提要(RSS)
网站聚合提要对于任何想要向其他系统分享信息的站点来说都是非常必要的.众所周知的格式有 RSS 和 Atom,没有模块处理的情况下生成对应的格式可能会非常耗时间. 由于Node强大的包管理工具 NPM, 从现在开始你可以随时随地快速生成属于你自己的内容聚合提要.
安装 feed 包
开始之前, 打开你的项目文件夹,然后安装 feed模块的最新版本:
1 $ npm install feed
生成 feed
首先, 我们需要初始化一个新的 Feed
对象.初始化feed对象的时候你必须提供和你想要生成的网站聚合提要相关的基本信息.
1 // Require module 2 var Feed = require('feed'); 3 4 // Initializing feed object 5 var feed = new Feed({ 6 title: 'My Feed Title', 7 description: 'This is my personnal feed!', 8 link: 'http://example.com/', 9 image: 'http://example.com/logo.png', 10 copyright: 'Copyright © 2013 John Doe. All rights reserved', 11 12 author: { 13 name: 'John Doe', 14 email: 'john.doe@example.com', 15 link: 'https://example.com/john-doe' 16 } 17 });
第二,你可能想确定您的feed主题. 无论是RSS还是 Atom,两种格式都提供了识别一个或一个以上分类的功能. 再强调一遍,这真的超容易实现:
1 feed.category('Node.js'); 2 feed.category('JavaScript');
第三, 每一个 feed 至少需要一个条目 (比如常用的条目).这样你就必须用 item
函数,然后提供合适的对象. 当然如果你运行的是一个内容网站(比如博客!), 你可能会有多个条目. 使用一个for循环来填充生成你的feed,如下所示
:
1 for(var key in posts) { 2 feed.item({ 3 title: posts[key].title, 4 link: posts[key].url, 5 description: posts[key].description, 6 date: posts[key].date 7 }); 8 }
到这里为止, 生成RSS或者Atom的准备工作已经全部完成了. 使用 render函数
:
1 var output = feed.render();
这样隐式调用了 render
请求. 通常来讲, 这么做会生成一个RSS feed. 你也可以使用一个更为显式的方法, 可以让你选择要生成 RSS还是Atom :
1 // Rendering a RSS 2.0 valid feed 2 feed.render('rss-2.0'); 3 4 // Rendering an Atom 1.0 valid feed 5 feed.render('atom-1.0');
对,就是这么简单!
使用 Express.js
Express.js来做 feed
非常容易上手. 比如你可以用 app.get()
方法来按指定的路径发送rss
. 发送了feed之后,就可以像我们之前说过的那样呈现你的feed了. 然后,将 Content-Type
设置为 text/xml
来发送结果:
1 app.get('/rss', function(req, res) { 2 3 // Initializing feed object 4 var feed = new Feed({ 5 title: 'My Feed Title', 6 description: 'This is my personnal feed!', 7 link: 'http://example.com/', 8 image: 'http://example.com/logo.png', 9 copyright: 'Copyright © 2013 John Doe. All rights reserved', 10 11 author: { 12 name: 'John Doe', 13 email: 'john.doe@example.com', 14 link: 'https://example.com/john-doe' 15 } 16 }); 17 18 // Function requesting the last 5 posts to a database. This is just an 19 // example, use the way you prefer to get your posts. 20 Post.findPosts(function(posts, err) { 21 if(err) 22 res.send('404 Not found', 404); 23 else { 24 for(var key in posts) { 25 feed.item({ 26 title: posts[key].title, 27 link: posts[key].url, 28 description: posts[key].description, 29 date: posts[key].date 30 }); 31 } 32 // Setting the appropriate Content-Type 33 res.set('Content-Type', 'text/xml'); 34 35 // Sending the feed as a response 36 res.send(feed.render('rss-2.0')); 37 } 38 }); 39 });
结语
你看,这超容易 ! 现在立刻马上使用,大家很快就能用上你的Node.js应用来阅读你所有的feed了.
原文地址: http://howtonode.org/content-syndication-with-node
本文地址: http://zhangzexin.org/content-syndication-with-node-js/
转载请声明,谢谢。