Repository navigation
Expand file tree
/
Copy pathposts.js
More file actions
93 lines (78 loc) · 2.04 KB
/
Copy pathposts.js
File metadata and controls
93 lines (78 loc) · 2.04 KB
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
89
90
91
92
93
import fs from 'fs';
import path from 'path';
import process from 'process';
import matter from 'gray-matter';
import { remark } from 'remark';
import html from 'remark-html';
const postsDirectory = path.join(process.cwd(), 'posts');
export function getSortedPostsData() {
const fileNames = fs.readdirSync(postsDirectory);
const allPostsData = fileNames.map(fileName => {
// remove .md extension so id is the file name
const id = fileName.replace(/\.md$/, '');
// read md file as string
const fullPath = path.join(postsDirectory, fileName);
const fileContents = fs.readFileSync(fullPath, 'utf-8');
// use gray-matter to parse the markddown
// destructure drilling to grab all we need: title, date
const {
data: { title, date },
} = matter(fileContents);
// combine data and id
return {
id,
title,
date,
};
});
// sort posts by date
return allPostsData.sort(({ date: a }, { date: b }) => {
if (a < b) {
return 1;
} else if (a > b) {
return -1;
} else {
return 0;
}
});
}
export function getAllPostIds() {
const fileNames = fs.readdirSync(postsDirectory);
// Returns an array that looks like this:
// [
// {
// params: {
// id: 'ssg-ssr'
// }
// },
// {
// params: {
// id: 'pre-rendering'
// }
// }
// ]
return fileNames.map(fileName => {
return {
params: {
id: fileName.replace(/\.md$/, ''),
},
};
});
}
export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
// use remark to convert markdown to HTML string
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = String(processedContent);
// Combine the data with the id
return {
id,
contentHtml,
...matterResult.data,
};
}