-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (75 loc) · 2.15 KB
/
Copy pathserver.js
File metadata and controls
97 lines (75 loc) · 2.15 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require('path');
var marked = require('marked');
var app = express();
var PORT = process.env.PORT || 3000;
var NOTES_DIR = path.join(__dirname, 'notes');
if (!fs.existsSync(NOTES_DIR)) {
fs.mkdirSync(NOTES_DIR);
}
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
function sanitizeName(name) {
return name.replace(/[^a-z0-9-_ ]/gi, '').trim();
}
app.get('/api/notes', function (req, res) {
fs.readdir(NOTES_DIR, function (err, files) {
if (err) {
return res.status(500).json({ error: 'Unable to read notes' });
}
var notes = files
.filter(function (file) {
return file.endsWith('.md');
})
.map(function (file) {
return file.replace('.md', '');
});
res.json(notes);
});
});
app.get('/api/notes/:name', function (req, res) {
var name = sanitizeName(req.params.name);
var filePath = path.join(NOTES_DIR, name + '.md');
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
return res.status(404).json({ error: 'Note not found' });
}
res.json({
name: name,
content: data,
html: marked(data)
});
});
});
app.post('/api/notes/:name', function (req, res) {
var name = sanitizeName(req.params.name);
if (!name) {
return res.status(400).json({ error: 'Invalid note name' });
}
var filePath = path.join(NOTES_DIR, name + '.md');
var content = req.body.content || '';
fs.writeFile(filePath, content, function (err) {
if (err) {
return res.status(500).json({ error: 'Unable to save note' });
}
res.json({ success: true });
});
});
app.delete('/api/notes/:name', function (req, res) {
var name = sanitizeName(req.params.name);
var filePath = path.join(NOTES_DIR, name + '.md');
fs.unlink(filePath, function (err) {
if (err) {
return res.status(404).json({ error: 'Note not found' });
}
res.json({ success: true });
});
});
app.listen(PORT, function () {
console.log('Server running on http://localhost:' + PORT);
});
// polish
// tidy up
// small fix