-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
47 lines (33 loc) · 1.37 KB
/
server.mjs
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
import fs from 'fs'
import http from 'http'
import path from 'path'
const PORT = 50000
const USER_SCRIPT_FILE_NAME = 'gofile.user.js'
const MIME_TYPES = {
default: 'text/plain',
js: 'application/javascript',
}
const STATIC_PATH = path.join(process.cwd(), '.')
const toBool = [() => true, () => false]
const prepareFile = async (url) => {
const paths = [STATIC_PATH, url]
if (url.endsWith('/')) paths.push('index.html')
const filePath = path.join(...paths)
const pathTraversal = !filePath.startsWith(STATIC_PATH)
const exists = await fs.promises.access(filePath).then(...toBool)
const found = !pathTraversal && exists
const streamPath = found ? filePath : STATIC_PATH + '/404.html'
const ext = path.extname(streamPath).substring(1).toLowerCase()
const stream = fs.createReadStream(streamPath)
return { found, ext, stream }
}
http.createServer(async (req, res) => {
const file = await prepareFile(req.url)
const statusCode = file.found ? 200 : 404
const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default
res.writeHead(statusCode, { 'Content-Type': mimeType })
file.stream.pipe(res)
console.log(`${req.method} ${req.url} ${statusCode}`)
console.log(`userscript at http://localhost:${PORT}/${USER_SCRIPT_FILE_NAME}`)
}).listen(PORT)
console.log(`userscript at http://localhost:${PORT}/${USER_SCRIPT_FILE_NAME}`)