Files
astroplate/scripts/jsonGenerator.js
T

69 lines
1.8 KiB
JavaScript
Raw Normal View History

2023-04-17 12:50:29 +06:00
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
2023-12-11 15:00:43 +06:00
const CONTENT_DEPTH = 2;
const JSON_FOLDER = "./.json";
const BLOG_FOLDER = "src/content/blog";
2023-04-17 12:50:29 +06:00
// get data from markdown
2023-12-11 15:00:43 +06:00
const getData = (folder, groupDepth) => {
2023-12-19 08:52:26 +06:00
const getPath = fs.readdirSync(folder);
const removeIndex = getPath.filter((item) => !item.startsWith("-"));
2023-12-11 15:00:43 +06:00
2023-12-19 08:52:26 +06:00
const getPaths = removeIndex.flatMap((filename) => {
2023-12-11 15:00:43 +06:00
const filepath = path.join(folder, filename);
const stats = fs.statSync(filepath);
const isFolder = stats.isDirectory();
if (isFolder) {
return getData(filepath, groupDepth);
} else if (filename.endsWith(".md") || filename.endsWith(".mdx")) {
2023-12-19 08:52:26 +06:00
const file = fs.readFileSync(filepath, "utf-8");
const { data, content } = matter(file);
const pathParts = filepath.split(path.sep);
const slug =
data.slug ||
pathParts
.slice(CONTENT_DEPTH)
.join("/")
.replace(/\.[^/.]+$/, "");
const group = pathParts[groupDepth];
2023-12-11 15:00:43 +06:00
return {
group: group,
slug: slug,
frontmatter: data,
content: content,
};
2023-12-19 08:52:26 +06:00
} else {
return [];
2023-12-11 15:00:43 +06:00
}
2023-04-17 12:50:29 +06:00
});
2023-12-11 15:00:43 +06:00
const publishedPages = getPaths.filter(
(page) => !page.frontmatter?.draft && page,
2023-04-17 12:50:29 +06:00
);
return publishedPages;
};
try {
2023-12-11 15:00:43 +06:00
// create folder if it doesn't exist
if (!fs.existsSync(JSON_FOLDER)) {
fs.mkdirSync(JSON_FOLDER);
2023-04-17 12:50:29 +06:00
}
2023-12-11 15:00:43 +06:00
// create json files
fs.writeFileSync(
`${JSON_FOLDER}/posts.json`,
2023-12-19 08:52:26 +06:00
JSON.stringify(getData(BLOG_FOLDER, 2)),
2023-12-11 15:00:43 +06:00
);
// merger json files for search
const posts = require(`../${JSON_FOLDER}/posts.json`);
const search = [...posts];
fs.writeFileSync(`${JSON_FOLDER}/search.json`, JSON.stringify(search));
2023-04-17 12:50:29 +06:00
} catch (err) {
console.error(err);
}