The Node.js® Website
1import { existsSync, readFileSync } from 'node:fs';
2import { join } from 'node:path';
3import zlib from 'node:zlib';
4
5import { slug } from 'github-slugger';
6
7import { getRelativePath } from '../../next.helpers.mjs';
8
9const currentRoot = getRelativePath(import.meta.url);
10const dataBasePath = join(currentRoot, '../../.next/server/app/en/next-data');
11
12if (!existsSync(dataBasePath)) {
13 throw new Error(
14 'The data directory does not exist. Please run `npm run build` first.'
15 );
16}
17
18const nextPageData = readFileSync(`${dataBasePath}/page-data.body`, 'utf-8');
19const nextAPIPageData = readFileSync(`${dataBasePath}/api-data.body`, 'utf-8');
20
21const pageData = JSON.parse(nextPageData);
22const apiData = JSON.parse(nextAPIPageData);
23
24const splitIntoSections = markdownContent => {
25 const lines = markdownContent.split(/\n/gm);
26 const sections = [];
27
28 let section = null;
29
30 for (const line of lines) {
31 if (line.match(/^#{1,6}\s/)) {
32 section = {
33 pageSectionTitle: line.replace(/^#{1,6}\s*/, ''),
34 pageSectionContent: [],
35 };
36
37 sections.push(section);
38 } else if (section) {
39 section.pageSectionContent.push(line);
40 }
41 }
42
43 return sections.map(section => ({
44 ...section,
45 pageSectionContent: section.pageSectionContent.join('\n'),
46 }));
47};
48
49const getPageTitle = data =>
50 data.title ||
51 data.pathname
52 .split('/')
53 .pop()
54 .replace(/\.html$/, '')
55 .replace(/-/g, ' ');
56
57export const siteContent = [...pageData, ...apiData]
58 .map(data => {
59 const { pathname, title = getPageTitle(data), content } = data;
60 const markdownContent = zlib
61 .inflateSync(Buffer.from(content, 'base64'))
62 .toString('utf-8');
63
64 const siteSection = pathname.split('/').shift();
65 const subSections = splitIntoSections(markdownContent);
66
67 return subSections.map(section => {
68 return {
69 path: pathname + '#' + slug(section.pageSectionTitle),
70 siteSection,
71 pageTitle: title,
72 ...section,
73 };
74 });
75 })
76 .flat();