-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfrontmatter.js
75 lines (63 loc) · 2.12 KB
/
frontmatter.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
const fs = require("fs").promises;
const path = require("path");
const matter = require("gray-matter");
async function updateMarkdownFiles(directoryPath) {
try {
const entries = await fs.readdir(directoryPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(directoryPath, entry.name);
if (entry.isDirectory()) {
// Recursively process subdirectories
await updateMarkdownFiles(fullPath);
} else if (
entry.isFile() &&
path.extname(entry.name).toLowerCase() === ".md"
) {
await processMarkdownFile(fullPath);
}
}
} catch (err) {
console.error("Error processing directory:", directoryPath, err);
}
}
async function processMarkdownFile(filePath) {
try {
const content = await fs.readFile(filePath, "utf8");
// Skip empty files
if (content.trim() === "") {
console.log(`Skipping empty file: ${filePath}`);
return;
}
// Parse the content
const { data, content: markdownContent } = matter(content);
// Extract title from H1 heading
const titleMatch = markdownContent.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1] : "";
if (title) {
// Update or add the title in the frontmatter
data.title = title;
// Remove the H1 heading from the markdown content
const updatedMarkdownContent = markdownContent
.replace(/^#\s+(.+)$/m, "")
.trim();
// Stringify the updated frontmatter and content
const updatedContent = matter.stringify(updatedMarkdownContent, data);
// Write the updated content back to the file
await fs.writeFile(filePath, updatedContent);
console.log(`Updated frontmatter and removed H1 in ${filePath}`);
} else {
console.log(`No H1 heading found in ${filePath}`);
}
} catch (err) {
console.error(`Error processing file ${filePath}:`, err);
}
}
// Usage
const directoryPath = "./";
updateMarkdownFiles(directoryPath)
.then(() => {
console.log("Finished processing all markdown files.");
})
.catch((err) => {
console.error("An error occurred:", err);
});