-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
executable file
·102 lines (78 loc) · 2.35 KB
/
server.ts
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
#!/usr/bin/env node
import { unescape } from "querystring";
import * as fs from "fs";
import * as path from "path";
import * as portFinder from "portfinder";
import ejs from "ejs";
import express from "express";
import helmet from "helmet";
import logger from "morgan";
import open from "open";
const server = express();
server.use(helmet({
"contentSecurityPolicy": false
}));
server.set("json spaces", 4);
server.use(logger("dev"));
let username = "";
let repository = "";
let description = "";
const packageJsonFile = path.join(process.cwd(), "package.json");
if (fs.existsSync(packageJsonFile)) {
const parsedPackageJson = JSON.parse(fs.readFileSync(packageJsonFile, { "encoding": "utf8" }));
if (parsedPackageJson?.["repository"]?.["url"] !== undefined) {
const matches = new URL(parsedPackageJson["repository"]["url"]).pathname.split("/");
username = matches[1];
repository = path.basename(matches[2], path.extname(matches[2]));
}
if (parsedPackageJson["description"] !== undefined) {
description = parsedPackageJson["description"];
}
}
const basePath = process.cwd();
server.get("/", async function(request, response) {
response.send(await ejs.renderFile(path.join(__dirname, "index.html"), {
"username": username,
"repository": repository || path.basename(basePath),
"description": description
}));
});
server.get("*", function(request, response, next) {
const fullPath = path.join(basePath, unescape(request.path.replace("/~", "")));
if (path.resolve(fullPath).startsWith(basePath)) {
if (fs.existsSync(fullPath)) {
if (fs.statSync(fullPath).isFile()) {
response.sendFile(fullPath);
} else if (!(fullPath.endsWith("/") || fullPath.endsWith("\\"))) {
response.redirect(request.path + "/");
} else if (request.path.startsWith("/~/")) {
const files = [];
const folders = [];
for (const file of fs.readdirSync(fullPath)) {
if (fs.statSync(path.join(fullPath, file)).isFile()) {
files.push(file);
} else {
folders.push(file);
}
}
response.json({
"files": files,
"folders": folders
});
}
return;
}
}
response.status(404);
next();
});
portFinder.getPort(function(error, port) {
if (error) {
throw error;
}
server.listen(port, function() {
const url = "http://localhost:" + this.address().port + "/";
console.log("Listening on " + url);
open(url);
});
});