-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
40 lines (36 loc) · 1.16 KB
/
server.js
File metadata and controls
40 lines (36 loc) · 1.16 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
import { createServer } from 'http';
import { readdir, readFile } from 'fs/promises';
import path from 'path';
const storageDir = path.join(process.cwd(), 'storage');
async function readAll(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const result = {};
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
result[entry.name] = await readAll(fullPath);
} else {
result[entry.name] = await readFile(fullPath, 'utf-8');
}
}
return result;
}
const server = createServer(async (req, res) => {
if (req.method === 'GET' && req.url === '/api/files') {
try {
const data = await readAll(storageDir);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`server listening on http://localhost:${PORT}`);
});