forked from nodejs/nodejs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-documents.mjs
More file actions
80 lines (64 loc) · 2.11 KB
/
get-documents.mjs
File metadata and controls
80 lines (64 loc) · 2.11 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import zlib from 'node:zlib';
import { slug } from 'github-slugger';
import { getRelativePath } from '../../next.helpers.mjs';
const currentRoot = getRelativePath(import.meta.url);
const dataBasePath = join(currentRoot, '../../.next/server/app/en/next-data');
if (!existsSync(dataBasePath)) {
throw new Error(
'The data directory does not exist. Please run `npm run build` first.'
);
}
const nextPageData = readFileSync(`${dataBasePath}/page-data.body`, 'utf-8');
const nextAPIPageData = readFileSync(`${dataBasePath}/api-data.body`, 'utf-8');
const pageData = JSON.parse(nextPageData);
const apiData = JSON.parse(nextAPIPageData);
const splitIntoSections = markdownContent => {
const lines = markdownContent.split(/\n/gm);
const sections = [];
let section = null;
for (const line of lines) {
if (line.match(/^#{1,6}\s/)) {
section = {
pageSectionTitle: line.replace(/^#{1,6}\s*/, ''),
pageSectionContent: [],
};
sections.push(section);
} else if (section) {
section.pageSectionContent.push(line);
}
}
return sections.map(section => ({
...section,
pageSectionContent: section.pageSectionContent.join('\n'),
}));
};
const uppercaseFirst = string =>
string.charAt(0).toUpperCase() + string.slice(1);
const getPageTitle = data =>
data.title ||
data.pathname
.split('/')
.pop()
.replace(/\.html$/, '')
.replace(/-/g, ' ');
export const siteContent = [...pageData, ...apiData]
.map(data => {
const { pathname, title = getPageTitle(data), content } = data;
const markdownContent = zlib
.inflateSync(Buffer.from(content, 'base64'))
.toString('utf-8');
const siteSection = pathname.split('/').shift();
const subSections = splitIntoSections(markdownContent);
return subSections.map(section => {
const path = `${pathname}#${slug(section.pageSectionTitle)}`;
return {
path: path,
siteSection: uppercaseFirst(siteSection),
pageTitle: title,
...section,
};
});
})
.flat();