Created
May 15, 2020 19:56
-
-
Save bencleary/04ca08125f7a551ee55415f34f0e70da to your computer and use it in GitHub Desktop.
Generates a JSON index file that can be used for searching on your static site.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const toml = require("toml"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const inDirectory = path.join(__dirname, "..", "content", "posts"); | |
const outDirectory = path.join(__dirname, "..", "static", "assets", "js"); | |
class Index { | |
filePathQueue = []; | |
indexes = []; | |
slugify(title) { | |
return title.toLowerCase().replace(/\s+/g, "-"); | |
} | |
getItems(dir) { | |
try { | |
let items = fs.readdirSync(dir); | |
items.forEach((item) => { | |
let stat = fs.statSync(path.join(dir, item)); | |
if (stat && stat.isDirectory()) { | |
this.getItems(path.join(dir, item)); | |
} else { | |
if (!item.includes("git")) { | |
console.log("Found"); | |
this.filePathQueue.push(path.join(dir, item)); | |
} | |
} | |
}); | |
} catch (err) { | |
console.log(err); | |
} | |
return this; | |
} | |
parseFiles() { | |
this.filePathQueue.forEach((file) => { | |
try { | |
let contents = fs.readFileSync(file, "utf8"); | |
let parts = contents.split("+++"); | |
if (parts.length in [0, 1]) { | |
return; | |
} | |
let frontMatter = toml.parse(parts[1].trim()); | |
// windows currently | |
let pathParts = file.split("\\"); | |
// check if file in sub post directory | |
let category = pathParts[pathParts.length - 2]; | |
let hrefDirectory = "/posts/"; | |
if (category != "posts") { | |
hrefDirectory = `/posts/${category.toLowerCase()}/`; | |
} | |
let searchTemplate = { | |
title: frontMatter.title, | |
tags: frontMatter.tags, | |
href: `${hrefDirectory}${this.slugify(frontMatter.title)}`, | |
excerpt: frontMatter.excerpt, | |
}; | |
this.indexes.push(searchTemplate); | |
} catch (err) { | |
console.log(err); | |
} | |
}); | |
return this; | |
} | |
index(dir) { | |
fs.writeFileSync( | |
path.join(dir, "search.json"), | |
JSON.stringify(this.indexes) | |
); | |
} | |
} | |
new Index().getItems(inDirectory).parseFiles().index(outDirectory); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment