forked from MapComplete/MapComplete
Scripts: simplify studio-server
This commit is contained in:
parent
8c7f686931
commit
ee6e3558da
1 changed files with 18 additions and 14 deletions
|
@ -22,21 +22,19 @@ const MIME_TYPES = {
|
||||||
|
|
||||||
const STATIC_PATH = path.join(process.cwd(), "./assets")
|
const STATIC_PATH = path.join(process.cwd(), "./assets")
|
||||||
|
|
||||||
const toBool = [() => true, () => false]
|
async function prepareFile(url: string): Promise<string> {
|
||||||
|
|
||||||
const prepareFile: (url) => Promise<{ ext: string; found: boolean; stream: ReadStream }> = async (
|
|
||||||
url
|
|
||||||
) => {
|
|
||||||
const paths = [STATIC_PATH, url]
|
const paths = [STATIC_PATH, url]
|
||||||
if (url.endsWith("/")) paths.push("index.html")
|
if (url.endsWith("/")) paths.push("index.html")
|
||||||
const filePath = path.join(...paths)
|
const filePath = path.join(...paths)
|
||||||
const pathTraversal = !filePath.startsWith(STATIC_PATH)
|
const exists = fs.existsSync(filePath)
|
||||||
const exists = await fs.promises.access(filePath).then(...toBool)
|
console.log("Checking", filePath, exists)
|
||||||
const found = !pathTraversal && exists
|
const found = exists
|
||||||
const streamPath = found ? filePath : STATIC_PATH + "/404.html"
|
if (!found) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const streamPath = filePath
|
||||||
const ext = path.extname(streamPath).substring(1).toLowerCase()
|
const ext = path.extname(streamPath).substring(1).toLowerCase()
|
||||||
const stream = fs.createReadStream(streamPath)
|
return fs.readFileSync(streamPath, "utf8")
|
||||||
return { found, ext, stream }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
http.createServer(async (req, res) => {
|
http.createServer(async (req, res) => {
|
||||||
|
@ -86,10 +84,16 @@ http.createServer(async (req, res) => {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const file = await prepareFile(req.url)
|
const file = await prepareFile(req.url)
|
||||||
const statusCode = file.found ? 200 : 404
|
if (file === null) {
|
||||||
const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default
|
res.writeHead(404, { "Content-Type": MIME_TYPES.html })
|
||||||
|
res.write("<html><body><p>Not found...</p></body></html>")
|
||||||
|
res.end()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const statusCode = 200
|
||||||
|
const mimeType = MIME_TYPES.json || MIME_TYPES.default
|
||||||
res.writeHead(statusCode, { "Content-Type": mimeType })
|
res.writeHead(statusCode, { "Content-Type": mimeType })
|
||||||
file.stream.pipe(res)
|
res.write(file)
|
||||||
res.end()
|
res.end()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue