-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·86 lines (70 loc) · 1.92 KB
/
index.js
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
#!/usr/bin/env node
const http = require('http');
const path = require('path');
const fs = require('fs');
http.createServer(async function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
if (req.method === 'OPTIONS') {
res.end();
return;
}
else if (req.method !== 'GET') {
res.statusCode = 405;
res.write("Method not allowed");
res.end();
return;
}
const fsRoot = '.';
const reqPath = req.url;
if (reqPath.startsWith('/gemdrive/index') && reqPath.endsWith('list.json')) {
const itemPath = reqPath.slice('/gemdrive/index'.length, reqPath.length - 'list.json'.length);
const fsDir = path.join(fsRoot, path.dirname(itemPath));
let filenames;
try {
filenames = await fs.promises.readdir(fsDir);
}
catch (e) {
res.statusCode = 404;
res.write("Not Found");
res.end();
return;
}
const gemData = {
children: {},
};
for (const filename of filenames) {
const childFsPath = path.join(fsDir, filename);
const stats = await fs.promises.stat(childFsPath);
const name = stats.isDirectory() ? filename + '/' : filename;
gemData.children[name] = {
size: stats.size,
modTime: stats.mtime,
};
}
res.write(JSON.stringify(gemData, null, 2));
res.end();
}
else {
const fsPath = path.join(fsRoot, reqPath);
let stats
try {
stats = await fs.promises.stat(fsPath);
res.setHeader('Content-Length', `${stats.size}`);
stream = fs.createReadStream(fsPath);
stream.on('error', (e) => {
res.statusCode = 404;
res.write("Not Found");
res.end();
});
stream.pipe(res);
}
catch (e) {
res.statusCode = 404;
res.write("Not Found");
res.end();
return;
}
}
}).listen(9001);