]> git.r.bdr.sh - rbdr/blog/blob - lib/generators/rss.js
4ae39257244941db8e76821766b9ff8dfc1020af
[rbdr/blog] / lib / generators / rss.js
1 'use strict';
2
3 const { template, templateSettings } = require('dot');
4 const { encodeXML } = require('entities');
5 const { readFile, writeFile } = require('fs/promises');
6 const { join } = require('path');
7 const { debuglog } = require('util');
8
9 const internals = {
10 debuglog: debuglog('blog'),
11
12 kFeedName: 'feed.xml',
13
14 extractTitle(postText) {
15
16 return postText.trim()
17 .split('\n')[0]
18 .replace('#', '')
19 .replace(/&/g, '&')
20 .trim();
21 }
22 };
23
24 /**
25 * Generates an RSS feed XML file
26 *
27 * @name RSSGenerator
28 * @param {string} source the source directory
29 * @param {string} target the target directory
30 * @param {Array.<Blog.tPost>} posts the list of posts
31 */
32 module.exports = async function RSSGenerator(source, target, posts) {
33
34 internals.debuglog('Generating RSS');
35 const feedTarget = join(target, internals.kFeedName);
36 const feedLocation = join(source, internals.kFeedName);
37
38 internals.debuglog(`Reading ${feedLocation}`);
39 const feedTemplate = await readFile(feedLocation, { encoding: 'utf8' });
40
41 internals.debuglog('Writing RSS');
42 posts = posts.map((post) => ({
43 ...post,
44 createdOn: (new Date(post.createdOn)).toUTCString(),
45 title: internals.extractTitle(post.raw),
46 html: encodeXML(post.html)
47 }));
48 const feedXml = template(feedTemplate, {
49 ...templateSettings,
50 strip: false
51 })({ posts });
52 await writeFile(feedTarget, feedXml);
53 };