-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
73 lines (62 loc) · 2.17 KB
/
api.js
File metadata and controls
73 lines (62 loc) · 2.17 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
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
app.use(express.text());
// 1. LIHAT SEMUA DAFTAR CATATAN
app.get('/notes', (req, res) => {
const files = fs.readdirSync('./').filter(file => file.endsWith('.txt'));
res.send(files.length > 0 ? files : "Belum ada catatan.");
});
// 2. BACA isi catatan spesifik
app.get('/notes/:title', (req, res) => {
const fileName = `${req.params.title}.txt`;
if (fs.existsSync(fileName)) {
res.send(fs.readFileSync(fileName, 'utf8'));
} else {
res.status(404).send('Catatan tidak ditemukan');
}
});
// 3. SIMPAN catatan baru (dengan pengecekan error)
app.post('/notes/:title', (req, res) => {
const content = req.body || "";
if (!content) return res.status(400).send("Isi catatan tidak boleh kosong!");
fs.writeFileSync(`${req.params.title}.txt`, content);
res.send(`Catatan '${req.params.title}' berhasil disimpan!`);
});
// 4. HAPUS catatan
app.delete('/notes/:title', (req, res) => {
const fileName = `${req.params.title}.txt`;
if (fs.existsSync(fileName)) {
fs.unlinkSync(fileName);
res.send(`Catatan '${req.params.title}' telah dihapus.`);
} else {
res.status(404).send('Catatan tidak ditemukan');
}
});
app.listen(port, () => {
console.log(`Server aktif di http://localhost:${port}`);
});
// 5. EDIT/UPDATE ISI CATATAN (PUT /notes/:title)
app.put('/notes/:title', (req, res) => {
const fileName = `${req.params.title}.txt`;
const newContent = req.body || "";
if (fs.existsSync(fileName)) {
if (!newContent.trim()) {
return res.status(400).send("Isi baru tidak boleh kosong!");
}
fs.writeFileSync(fileName, newContent);
res.send(`Catatan '${req.params.title}' berhasil diperbarui!`);
} else {
res.status(404).send('Catatan tidak ditemukan, gunakan POST untuk membuat baru.');
}
});
// 6. FITUR DOWNLOAD
app.get('/download/:title', (req, res) => {
const fileName = `${req.params.title}.txt`;
if (fs.existsSync(fileName)) {
res.download(fileName);
} else {
res.status(404).send('File tidak ditemukan');
}
});