-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (82 loc) · 2.64 KB
/
index.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
89
90
91
let fs = require("fs");
let path = require("path");
const glob = require("glob");
const matter = require("gray-matter");
const postsDirectory = path.join(process.cwd() + "/posts");
const getAllSlugs = () => {
let slugs = [];
glob(postsDirectory + "/**/*.md", function (err, res) {
if (err) {
console.log("Error", err);
} else {
res.forEach((file) => {
const path = file.replace(postsDirectory, "");
const slug = path.replace("index.md", "").replace(".md", "");
slugs.push({ path: path, slug: slug });
});
fs.writeFileSync(
path.join(process.cwd(), "data", "all-slugs.json"),
JSON.stringify(slugs)
);
getMetaData(slugs);
}
});
};
const getMetaData = (slugs) => {
let metaData = [];
slugs.forEach((slug) => {
let filePath = path.join(process.cwd(), "posts", slug.path);
let file = fs.readFileSync(filePath, "utf8");
let meta = matter(file);
if (meta.data.draft === true) return;
meta.data["slug"] = slug.slug;
metaData.push(meta.data);
const fileName = slug.slug.replace(/[\\/:"*?<>|]/g, "") + ".json";
fs.writeFileSync(
path.join(process.cwd(), "data/posts", fileName),
JSON.stringify(meta.content)
);
});
// sort metaData by published date
metaData.sort((a, b) => {
return new Date(b.published) - new Date(a.published);
});
fs.writeFileSync(
path.join(process.cwd(), "data", "meta-data.json"),
JSON.stringify(metaData)
);
// get 10 latest posts
let latestPosts = metaData.slice(0, 10);
fs.writeFileSync(
path.join(process.cwd(), "data", "latest-posts.json"),
JSON.stringify(latestPosts)
);
getAllTags(metaData);
};
const getAllTags = (posts) => {
let tags = [];
posts.forEach((post) => {
post.tags.forEach((tag) => {
if (!tags.includes(tag)) {
tags.push(tag);
}
});
});
fs.writeFileSync(
path.join(process.cwd(), "data", "all-tags.json"),
JSON.stringify(tags)
);
getPostsByTag(tags, posts);
};
const getPostsByTag = (tags, metaData) => {
tags.forEach((tag) => {
let posts = metaData.filter((post) => {
return post.tags.includes(tag);
});
fs.writeFileSync(
path.join(process.cwd(), "data/tags", tag + ".json"),
JSON.stringify(posts)
);
});
};
getAllSlugs();