-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
116 lines (103 loc) · 3.01 KB
/
server.js
File metadata and controls
116 lines (103 loc) · 3.01 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const Express = require('express');
const Http = require('node:http');
const Path = require('node:path');
const Fs = require('node:fs');
const app = Express();
// Create database directory if needed
const dataPath = Path.resolve('./data');
if (!Fs.existsSync(dataPath)) {
Fs.mkdirSync(dataPath);
}
// Listen for uploads
const storeFile = (content, id) => {
return new Promise((resolve, reject) => {
Fs.readdir(dataPath, (err, list) => {
if (err) { return reject(err); }
const max = Math.max(...list.map(Number).filter(Boolean), 0);
const fileName = id || String(max + 1);
const filePath = Path.join(dataPath, fileName);
Fs.writeFile(filePath, content, err => {
if (err) { return reject(err); }
resolve({id: fileName});
});
});
});
};
app.use('/upload', (req, res) => {
let content = '';
const id = req.query.id;
req.on('data', data => {
content += data;
});
req.on('end', () => {
storeFile(content, id).then(json => {
res.status(200).send(json);
}).catch(err => {
res.status(500).send(err);
})
});
});
async function readFile(filePath) {
const readStream = Fs.createReadStream(filePath, {
encoding: 'utf8',
highWaterMark: 1024
});
let md = '';
let found = false;
try {
for await (const chunk of readStream) {
const idx = chunk.indexOf('|');
if (idx !== -1) {
md += chunk.slice(0, idx);
found = true;
break;
}
md += chunk;
}
} catch (error) {
console.error(`Error reading file ${filePath}: ${error.message}`);
}
if (!found) { return; }
let stat;
try {
stat = await new Promise((resolve, reject) => {
Fs.stat(filePath, (err, value) => {
if (err) { return reject(err); }
resolve(value);
});
});
} catch (e) {}
return {
metadata: md,
stat: {
mtime: +stat?.mtime,
ctime: +stat?.birthtime || +stat?.ctime
}
};
}
app.get('/list', (req, res) => {
Fs.readdir(dataPath, (err, list) => {
if (err) { return reject(err); }
const names = []
const promises = [];
list.forEach(name => {
names.push(name);
promises.push(readFile(Path.join(dataPath, name)));
});
Promise.all(promises).then(values => {
const json = {};
names.forEach((name, idx) => {
json[name] = values[idx];
});
res.status(200).send(json);
});
});
});
app.use('/data', Express.static(dataPath));
app.use('/components', Express.static(Path.resolve('./components')));
app.use(Express.static(Path.resolve('./examples')));
app.use((req, res) => {
res.status(404).send({});
});
const httpServer = Http.createServer(app);
httpServer.listen(4000, '::');