77 lines
1.9 KiB
JavaScript
77 lines
1.9 KiB
JavaScript
const fs = require('fs');
|
|
const S = require('string');
|
|
const path = require('path');
|
|
|
|
const CONTENT_PATH_PREFIX = 'content/'
|
|
const OUTPUT_PATH = "static/js/lunr/PagesIndex.json"
|
|
|
|
const getTree = dir => {
|
|
const allFiles = [];
|
|
|
|
const items = fs.readdirSync(dir);
|
|
items.forEach(item => {
|
|
const itemPath = path.join(dir, item);
|
|
const stats = fs.statSync(itemPath);
|
|
if (stats.isDirectory()) {
|
|
allFiles.push(...getTree(itemPath));
|
|
} else {
|
|
allFiles.push(itemPath);
|
|
}
|
|
});
|
|
return allFiles;
|
|
}
|
|
|
|
const pageIndices = getTree(CONTENT_PATH_PREFIX)
|
|
.map(file => {
|
|
const href = S(file).chompLeft(CONTENT_PATH_PREFIX).chompRight('.md').s;
|
|
|
|
if (href.startsWith('_')) {
|
|
return;
|
|
}
|
|
|
|
const content = fs.readFileSync(file).toString();
|
|
|
|
const splitContent = content.split('---')
|
|
const frontMatter = {};
|
|
try {
|
|
const frontMatterRaw = splitContent[1].trim();
|
|
|
|
for (const line of frontMatterRaw.split('\n')) {
|
|
try {
|
|
const parts = line.split(':');
|
|
const key = parts[0].trim()
|
|
const value = JSON.parse(parts[1]);
|
|
|
|
frontMatter[key] = value;
|
|
} catch (e) {
|
|
continue;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
return;
|
|
}
|
|
|
|
if (frontMatter.draft !== false) {
|
|
return;
|
|
}
|
|
|
|
const pageIndex = {}
|
|
|
|
pageIndex['title'] = frontMatter.title;
|
|
pageIndex['href'] = href;
|
|
pageIndex['content'] = S(splitContent[2]).trim().stripTags().stripPunctuation().s;
|
|
|
|
if (frontMatter.tags) {
|
|
pageIndex['tags'] = frontMatter.tags;
|
|
}
|
|
|
|
return pageIndex;
|
|
})
|
|
.filter(e => e)
|
|
;
|
|
|
|
fs.mkdirSync(path.dirname(OUTPUT_PATH), {
|
|
recursive: true,
|
|
});
|
|
fs.writeFileSync(OUTPUT_PATH, JSON.stringify(pageIndices));
|