forked from LudicrousDevelopment/Ludi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.mjs
31 lines (27 loc) · 1.18 KB
/
serve.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
// Equivalent to node-static or express.static.
import mime from 'mime'
import { readFileSync } from 'fs'
var defaults = {
indexfile: true,
'404': null,
'403': null,
'index': null
}
export function Serve(path, config, cors) {
var config = Object.assign(defaults, config)
return function(req, res, cors) {
var type = mime.getType(req.url.split('?')[0].split('#')[0])||'text/html'
if (req) {
try {
var url = path+req.url.split('?')[0].split('#')[0]
if (req.url.split('?')[0].split('#')[0]=='/'&&config.indexfile==true) {url+='index.html'}
try {readFileSync(url)} catch {/*if (config['404']) return config['404'](req, res)*/;return res.end('Not Found')}
if (req.url.split('?')[0].split('#')[0]=='/'&&config.indexfile==true) {if (config.index) return config.index(req, res, readFileSync(url), type)}
return res.writeHead(200, {'content-type':type, 'access-control-allow-origin':cors?'*':request.headers['host'],'service-worker-allowed':cors?'/':null}).end(readFileSync(url))
} catch(e) {return res.end(e.toString())}
} else {
throw new Error('Request Object: Expected [object Request], got undefined')
}
}
}
export default Serve