-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstatic-server.js
More file actions
68 lines (62 loc) · 2.03 KB
/
Copy pathstatic-server.js
File metadata and controls
68 lines (62 loc) · 2.03 KB
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
const http = require('http')
const fs = require('fs')
const path = require('path')
const mime = require('node-mime-types')
const fenrirDirectory = path.join(__dirname)
const kujataDataDirectory = path.join(__dirname, '..', 'kujata-data')
const addCors = res => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET')
res.setHeader('Access-Control-Max-Age', 2592000) // 30 days
res.setHeader('Access-Control-Allow-Headers', 'content-type') // Might be helpful
}
const server = http.createServer((req, res) => {
let cacheControlHeader = 'public, max-age=0'
let sourceDirectory = fenrirDirectory
if (req.url.startsWith('/kujata-data')) {
cacheControlHeader = 'public, max-age=604800'
sourceDirectory = kujataDataDirectory
req.url = decodeURI(req.url.substring(12).split('?')[0])
if (
req.url.startsWith('/data/field/') ||
req.url.startsWith('/data/battle/') ||
req.url.startsWith('/metadata/background-layers/')
) {
cacheControlHeader = 'public, max-age=0'
}
} else {
req.url = decodeURI(req.url.split('?')[0])
}
// if (
// (req.url.startsWith('/metadata') && req.url.endsWith('.png')) ||
// req.url.endsWith('.zip')
// ) {
// console.log('file', req.url)
// }
const filePath = path.join(
sourceDirectory,
req.url === '/' ? 'index.html' : decodeURI(req.url)
)
fs.stat(filePath, (err, stats) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('404 Not Found\n')
return
}
if (stats.isFile()) {
res.setHeader('Cache-Control', cacheControlHeader)
res.setHeader(
'Content-Type',
mime.getMIMEType(filePath) || 'application/octet-stream'
)
addCors(res)
fs.createReadStream(filePath).pipe(res)
} else {
res.writeHead(403, { 'Content-Type': 'text/plain' })
res.end('403 Forbidden\n')
}
})
})
server.listen(3000, () => {
console.log('Fenrir and kujata-data running on http://localhost:3000')
})