1const fs = require("fs");
2const path = require("path");
3const matter = require("gray-matter");
4const toml = require("@iarna/toml");
6// node ./buildPageTree.js [directory] [sort]
7// eg. node ./buildPageTree docs weight
8// will produce docs.json in the cache folder.
12 toml: toml.parse.bind(toml),
19 * buildPageTree is written to provide a recursive index of posts
20 * for nested directories for creating sidebars
21 * @param {string} path Absolute path to the subdirectory.
22 * @returns {Object.<string,string|Object<string,string[]|number>>} Title of the directory, child pages, and child directories (recursive structure).
34// children: { [string]: PageTree },
37function buildPageTree(dirPath, ordering = "", content = false) {
38 const metadata = matter(
39 fs.readFileSync(path.join(dirPath, "_index.md")),
42 // get a list of contents at the dirPath, with file types so that the item at the dirPath can be identified as file or folder
43 const children = fs.readdirSync(dirPath, { withFileTypes: true });
44 // get a list of files
45 const pages = children.filter((f) => f.isFile() && f.name !== "_index.md");
46 // get a list of folders
47 const subdirs = children.filter((f) => f.isDirectory());
48 // return a pagetree datastructure
50 title: metadata.data.title,
53 // retrieve topmatter as JSON
54 const { content, data } = matter(
55 fs.readFileSync(path.join(dirPath, page.name)),
63 slug: page.name.replace(/.md$/, ""),
64 ...(ordering === "weight" && { weight: data?.weight ?? 0 }),
65 ...(ordering === "date" && {
66 date: data?.date ?? "2000-01-01T00:00:00.000Z",
70 .sort((a, b) => a.weight - b.weight),
71 children: Object.fromEntries(
74 const aMetadata = matter(
75 fs.readFileSync(path.join(dirPath, a.name, "_index.md")),
78 const bMetadata = matter(
79 fs.readFileSync(path.join(dirPath, b.name, "_index.md")),
82 return aMetadata?.data?.weight - bMetadata?.data?.weight || 0;
86 buildPageTree(path.join(dirPath, subdir.name), ordering, content),
92const process = require("process");
94const arg = process.argv?.[2];
95const sort = process?.argv?.[3] || "weight";
97const dir = buildPageTree(path.join(process.cwd(), `content/${arg}`), sort);
98const fileContents = `${JSON.stringify(dir)}`;
101 fs.readdirSync("cache");
103 fs.mkdirSync("cache");
106fs.writeFile(`cache/${arg}.json`, fileContents, function (err) {
107 if (err) return console.error(err);
108 console.log(`${arg} directory structure created.`);
111module.exports = { buildPageTree };
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list