on roller-tutorial help sign in
urbit.org/lib/cache.js
73 lines 1.8 kB history raw
1const fs = require("fs");
2const path = require("path");
3const matter = require("gray-matter");
4const toml = require("@iarna/toml");
6const options = {
7 engines: {
8 toml: toml.parse.bind(toml),
9 },
10 language: "toml",
11 delimiters: "+++",
12};
14const index = [];
16function buildSearchIndex(dir) {
17 const dirName = dir.split("/").slice(-1).join("");
18 let metadata = {
19 data: {
20 title: dirName.charAt(0).toUpperCase() + dirName.slice(1),
21 },
22 };
24 try {
25 metadata = matter(fs.readFileSync(path.join(dir, "_index.md")), options);
26 } catch (err) {}
28 const children = fs.readdirSync(dir, { withFileTypes: true });
29 const pages = children.filter((f) => f.isFile() && f.name !== "_index.md");
30 const subdirs = children.filter((f) => f.isDirectory());
32 index.push(
33 ...pages.map((page) => {
34 const { data: pageData, content: pageContent } = matter(
35 fs.readFileSync(path.join(dir, page.name)),
36 options
37 );
38 return {
39 title: pageData.title,
40 base: page.name,
41 slug: path.join(
42 dir.substr(dir.indexOf("content") + 7),
43 "/",
44 page.name.replace(/.md$/, "")
45 ),
46 content: pageData.description || "",
47 parent: metadata.data.title,
48 };
49 })
50 );
52 Object.fromEntries(
53 subdirs.map((subdir) => [
54 subdir.name,
55 buildSearchIndex(path.join(dir, subdir.name)),
56 ])
57 );
60buildSearchIndex(path.join(process.cwd(), "content"));
62const fileContents = `export const index = ${JSON.stringify(index)}`;
64try {
65 fs.readdirSync("cache");
66} catch (err) {
67 fs.mkdirSync("cache");
70fs.writeFile("cache/data.js", fileContents, function (err) {
71 if (err) return console.error(err);
72 console.log("Site index created.");
73});