refactor: use async IO in blog.js, and stop postList generation for blog page

This commit is contained in:
William Oldham 2025-01-20 15:23:34 +00:00
parent 1c1e453213
commit d7009330f0

View File

@ -1,5 +1,5 @@
const fs = require('fs');
const path = require('path');
const fs = require('fs-extra');
const { Router } = require('express');
const { marked } = require('marked');
const matter = require('gray-matter');
@ -7,34 +7,35 @@ const logger = require('../logger');
const router = new Router();
const postList = () => {
const files = fs.readdirSync('blogposts');
async function getPostsList() {
const files = await fs.readdir('blogposts');
// We get the info for each blogpost, ignoring the ones starting with _
const posts = files
.filter(filename => !filename.startsWith('_'))
.filter(filename => filename.endsWith('.md')) // Ignores other files/folders
.map((filename) => {
const slug = filename.replace('.md', '');
const rawPost = fs.readFileSync(
path.join('blogposts', `${filename}`),
'utf-8'
);
const { data: postInfo } = matter(rawPost);
return {
slug,
postInfo
};
});
const filteredFiles = files
.filter(filename => !filename.startsWith('_')) // Ignore files starting with _
.filter(filename => filename.endsWith('.md')); // Ignores files that don't end with .md
const posts = await Promise.all(filteredFiles.map(async (filename) => {
const slug = filename.replace('.md', '');
const rawPost = await fs.readFile(
path.join('blogposts', `${filename}`),
'utf-8'
);
const { data: postInfo } = matter(rawPost);
return {
slug,
postInfo
};
}));
posts.sort((a, b) => {
return new Date(b.postInfo.date) - new Date(a.postInfo.date);
});
return posts;
};
}
router.get('/', async (request, response) => {
const postList = await getPostsList();
const renderData = {
postList
};
@ -44,8 +45,10 @@ router.get('/', async (request, response) => {
// RSS feed
router.get('/feed.xml', async (request, response) => {
const postList = await getPostsList();
// Adds the pubDate and the cover_extension to the post array
const posts = postList().map((post) => {
const posts = postList.map((post) => {
post.postInfo.pubDate = new Date(post.postInfo.date).toUTCString();
post.postInfo.cover_extension = post.postInfo.cover_image.substring(post.postInfo.cover_image.lastIndexOf('.') + 1);
return post;
@ -60,8 +63,7 @@ router.get('/feed.xml', async (request, response) => {
router.get('/:slug', async (request, response, next) => {
const renderData = {
layout: 'blog-opengraph',
postList
layout: 'blog-opengraph'
};
// Get the name of the post from the URL
@ -70,7 +72,7 @@ router.get('/:slug', async (request, response, next) => {
// Get the markdown file corresponding to the post
let rawPost;
try {
rawPost = fs.readFileSync(path.join('blogposts', `${postName}.md`), 'utf-8');
rawPost = await fs.readFile(path.join('blogposts', `${postName}.md`), 'utf-8');
} catch (err) {
logger.error(err);
next();