-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
72 lines (60 loc) · 2.01 KB
/
app.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
61
62
63
64
65
66
67
68
69
70
71
72
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const marked = require('marked');
// Set options
marked.use({
mangle: false,
headerIds: false
});
const app = express();
const PORT = process.env.PORT || 3000;
const markdownFolder = path.join(__dirname, 'markdown_files');
app.use(express.static('public'));
app.get('/files', async (req, res) => {
try {
const files = await readMarkdownFiles(markdownFolder);
res.json({ files });
} catch (err) {
res.status(500).json({ error: 'Error reading the folder' });
}
});
app.get('/_file/:filepath(*)', async (req, res) => {
const filepath = req.params.filepath.replace(/-/g, ' ');
const filePath = path.join(markdownFolder, filepath);
try {
const data = await fs.readFile(filePath, 'utf8');
const htmlContent = await marked.parse(data);
res.send(htmlContent);
} catch (err) {
res.status(404).send('File not found');
}
});
// Catch-all route to serve index.html for specific URLs
app.get('/file/:filepath(*)', (req, res, next) => {
// Check if the requested URL matches the desired format (e.g., "url/file/filename.md")
const filepath = req.params.filepath;
if (filepath.endsWith('.md')) {
// Serve the index.html file
res.sendFile(path.join(__dirname, 'public', 'index.html'));
} else {
// Handle other routes
next();
}
});
async function readMarkdownFiles(folderPath) {
const files = [];
const entries = await fs.readdir(folderPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const subFiles = await readMarkdownFiles(path.join(folderPath, entry.name));
files.push(...subFiles);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
files.push(path.relative(markdownFolder, path.join(folderPath, entry.name)));
}
}
return files;
}
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});