forked from AdmiralPotato/minimal_static_site_generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.js
More file actions
45 lines (40 loc) · 1.45 KB
/
shared.js
File metadata and controls
45 lines (40 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { readFile } from 'fs/promises';
import { join, basename, normalize } from 'path/posix';
export const parseFrontMatter = (frontMatterString) => {
const result = {};
const lines = frontMatterString.split('\n');
lines.forEach((line) => {
const keyValueRegex = /^(.*?): (.*)/mg;
const regexResult = keyValueRegex.exec(line.trim());
// console.log('What is regexResult?', regexResult);
if (!regexResult) {
return;
}
const [_wholeMatch, key, value] = regexResult;
result[key.trim()] = value.trim();
});
return result;
};
export const readMarkdownWithFrontMatter = async (scanPath, path) => {
const inputPath = normalize(join(scanPath, path));
const content = await readFile(inputPath, { encoding: 'utf8' });
// console.log('What is content?', content);
const frontMatterRegex = /^---\n(.*?)\n---\n/s;
const regexResult = frontMatterRegex.exec(content);
// console.log('What is regexResult?', regexResult);
if (!regexResult) {
throw new Error(`Your markdown needs frontMatter!\nFile: "${inputPath}"`);
}
const [remove, frontMatterString] = regexResult;
const markdown = content.replace(remove, '').trim();
const frontMatter = parseFrontMatter(frontMatterString);
return {
frontMatter,
markdown,
contentPath: normalize(inputPath.replace(basename(inputPath), '')),
};
}
const unwrapRegex = /^['"](.*)['"]$/;
export const unwrapString = (string) => {
return unwrapRegex.exec(string)[1];
}