Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80539 views
1
require('../shared/init');
2
3
import frontmatter from 'front-matter';
4
import { writeFile, readFile } from 'mz/fs';
5
import path from 'path';
6
import readdirp from 'readdirp';
7
import _mkdirp from 'mkdirp';
8
import { map, writeArray } from 'event-stream';
9
10
const docsRoot = path.join(process.cwd(), 'docs');
11
const dataRoot = path.join(process.cwd(), 'public/flummox/data');
12
13
const docStream = readdirp({ root: docsRoot, fileFilter: '*.md' })
14
.pipe(map((entry, cb) => {
15
async () => {
16
const { fullPath, path } = entry;
17
18
const contents = await readFile(fullPath, 'utf8');
19
20
const { attributes, body } = frontmatter(contents);
21
22
return {
23
path: path.slice(0, -3), // remove .md extension
24
content: body,
25
...attributes,
26
};
27
}()
28
.then(
29
result => cb(null, result),
30
err => cb(err)
31
);
32
}));
33
34
// Write to individual JSON document
35
docStream.pipe(map((doc, cb) => {
36
async () => {
37
const dest = path.format({
38
root: '/',
39
dir: path.join(dataRoot, 'docs', path.dirname(doc.path)),
40
base: `${path.basename(doc.path)}.json`,
41
});
42
43
const dir = path.dirname(dest);
44
45
await mkdirp(dir);
46
47
await writeFile(dest, JSON.stringify(doc));
48
}()
49
.then(
50
() => cb(null),
51
err => cb(err)
52
);
53
}));
54
55
// Write combined JSON document
56
docStream.pipe(writeArray((_, docs) => {
57
writeFile(path.join(dataRoot, 'allDocs.json'), JSON.stringify(docs));
58
}));
59
60
function mkdirp(dir) {
61
return new Promise((resolve, reject) => _mkdirp(dir, (err) => {
62
if (err) reject(err);
63
resolve();
64
}));
65
}
66
67