-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerateContentRoutes.js
60 lines (49 loc) · 1.65 KB
/
generateContentRoutes.js
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
const fs = require('fs').promises;
const path = require('path');
const contentDir = path.join(process.cwd(), 'content');
async function walkDir(dir) {
let filesList = [];
const files = await fs.readdir(dir, { withFileTypes: true });
for (const file of files) {
const res = path.resolve(dir, file.name);
if (file.isDirectory()) {
filesList = filesList.concat(await walkDir(res));
} else if (file.isFile() && path.extname(file.name).toLowerCase() === '.md' || path.extname(file.name) != 'yml') {
filesList.push(res);
}
}
return filesList;
}
function filePathToRoute(filePath) {
let route = filePath
.replace(contentDir, '')
.replace(/\.md$/, '')
.replace(/\\/g, '/'); // Reemplazar backslashes con forward slashes para compatibilidad
// Manejar index.md
if (route.endsWith('/index')) {
route = route.replace('/index', '');
}
// Manejar _dir.md (directorios)
route = route.replace(/\/_([^/]+)/g, '');
// Eliminar números al inicio de los segmentos de la ruta
route = route.split('/').map(segment => segment.replace(/^\d+\./, '')).join('/');
// Asegurarse de que la ruta comience con '/'
if (!route.startsWith('/')) {
route = '/' + route;
}
return route || '/';
}
async function generateContentRoutes() {
const filePaths = await walkDir(contentDir);
const routes = filePaths.map(filePath => filePathToRoute(filePath));
return routes;
}
generateContentRoutes()
.then(routes => {
console.log('Content Routes:');
console.log(JSON.stringify(routes, null, 2));
})
.catch(error => {
console.error('Error generating routes:', error);
});
module.exports = generateContentRoutes;