diff --git a/app.js b/app.js index 7e97d2d..5c5e44d 100644 --- a/app.js +++ b/app.js @@ -5,6 +5,7 @@ const fs = require('fs'); const { marked } = require('marked'); const nodemailer = require('nodemailer'); const hljs = require('highlight.js'); +const { format } = require('date-fns'); // To format dates in a proper XML format const app = express(); @@ -202,6 +203,58 @@ app.get('/blog/:slug', (req, res) => { } }); + +// Sitemap Route +app.get('/sitemap.xml', (req, res) => { + const hostname = req.headers.host || 'http://localhost'; // Ensure this is your site URL in production + const blogFiles = fs.readdirSync(path.join(__dirname, 'markdown')).filter(file => file.endsWith('.md')); + + // Static URLs (e.g., homepage, about, contact) + const staticUrls = [ + { url: '/', changefreq: 'weekly', priority: 1.0 }, + { url: '/about', changefreq: 'monthly', priority: 0.8 }, + { url: '/contact', changefreq: 'monthly', priority: 0.8 } + ]; + + // Dynamic URLs (e.g., blog posts) + const blogUrls = blogFiles.map(file => { + const title = file.replace('.md', ''); + const slug = titleToSlug(title); + + // Get the last modified date of the markdown file + const stats = fs.statSync(path.join(__dirname, 'markdown', file)); + const lastModifiedDate = format(new Date(stats.mtime), 'yyyy-MM-dd'); + + return { + url: `/blog/${slug}`, + lastmod: lastModifiedDate, + changefreq: 'monthly', + priority: 0.9 + }; + }); + + // Combine static and dynamic URLs + const urls = [...staticUrls, ...blogUrls]; + + // Generate the XML for the sitemap + let sitemap = `\n\n`; + urls.forEach(({ url, lastmod, changefreq, priority }) => { + sitemap += ` \n`; + sitemap += ` ${hostname}${url}\n`; + if (lastmod) { + sitemap += ` ${lastmod}\n`; + } + sitemap += ` ${changefreq}\n`; + sitemap += ` ${priority}\n`; + sitemap += ` \n`; + }); + sitemap += ``; + + // Set the content type to XML and send the response + res.header('Content-Type', 'application/xml'); + res.send(sitemap); +}); + // Global 404 handler for any other unmatched routes app.use((req, res) => { res.redirect('/'); // Redirect to the home page for any 404 error diff --git a/package.json b/package.json index a31bce0..f0e86bf 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dependencies": { "body-parser": "^1.20.3", "bootstrap": "^5.3.3", + "date-fns": "^4.0.0", "dotenv": "^16.4.5", "ejs": "^3.1.10", "express": "^4.21.0",