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;
2023-12-11 15:00:43 +06:00
const JSON_FOLDER = "./.json";
const BLOG_FOLDER = "src/content/blog";
2023-04-17 12:50:29 +06:00
// get data from markdown
const getData = (folder, groupDepth) => {
const getPath = fs.readdirSync(folder);
const removeIndex = getPath.filter((item) => !item.startsWith("-"));
2023-12-11 15:00:43 +06:00
const getPaths = removeIndex.flatMap((filename) => {
const filepath = path.join(folder, filename);
const stats = fs.statSync(filepath);
const isFolder = stats.isDirectory();
2024-05-27 11:31:07 +06:00
if (isFolder) {
return getData(filepath, groupDepth);
} else if (filename.endsWith(".md") || filename.endsWith(".mdx")) {
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,
};
} else {
return [];
}
});
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`,
JSON.stringify(getData(BLOG_FOLDER, 2)),
2023-12-11 15:00:43 +06:00
);
// merger json files for search
2023-12-11 15:00:43 +06:00
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);
}