forked from trofim24/api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
53 lines (43 loc) · 1.49 KB
/
app.js
File metadata and controls
53 lines (43 loc) · 1.49 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
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const marked = require('marked');
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;
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');
}
});
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}`);
});