-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-rss.js
88 lines (76 loc) · 2.51 KB
/
generate-rss.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// generate-rss.js
const fs = require('fs');
const path = require('path');
// Path to your blog-index.json file
const blogIndexPath = path.join(__dirname, 'data', 'blog-index.json');
// Output RSS feed file
const outputPath = path.join(__dirname, 'feed.xml');
// Your website's base URL (update with your actual domain)
const siteUrl = 'https://dame.is';
// Read the JSON file with blog posts
fs.readFile(blogIndexPath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading blog-index.json:', err);
return;
}
let blogData;
try {
blogData = JSON.parse(data);
} catch (jsonError) {
console.error('Error parsing JSON:', jsonError);
return;
}
const posts = blogData.posts || [];
// Sort posts in descending order by date (most recent first)
posts.sort((a, b) => new Date(b.date) - new Date(a.date));
// Get the current date for the RSS channel's lastBuildDate
const lastBuildDate = new Date().toUTCString();
// Generate the RSS <item> entries from your posts data
const rssItems = posts.map(post => {
// Construct the URL for the individual blog post.
// Adjust the URL if your post URLs differ.
const postUrl = `${siteUrl}/blog/${post.slug}`;
// Convert the date to an RFC 822 format using toUTCString()
const pubDate = new Date(post.date).toUTCString();
return `
<item>
<title>${escapeXml(post.title)}</title>
<link>${postUrl}</link>
<description><![CDATA[${post.excerpt} <a href="${postUrl}">Read More</a>]]></description>
<pubDate>${pubDate}</pubDate>
<guid>${postUrl}</guid>
</item>`;
}).join('');
// Assemble the complete RSS feed
const rssFeed = `<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>Dame's Blog</title>
<link>${siteUrl}</link>
<description>The latest posts from Dame's Blog</description>
<language>en-us</language>
<lastBuildDate>${lastBuildDate}</lastBuildDate>
${rssItems}
</channel>
</rss>`;
// Write the RSS feed to the output file
fs.writeFile(outputPath, rssFeed.trim(), err => {
if (err) {
console.error('Error writing feed.xml:', err);
} else {
console.log('RSS feed generated successfully!');
}
});
});
// Helper function to escape special XML characters
function escapeXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
}
});
}