-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
93 lines (71 loc) · 2.1 KB
/
server.js
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
var http = require('http')
var Path = require('path')
var fs = require('fs')
var region = require('./reader')
var regionList = require('./regionlist')
var config = require('./config')
var Watcher = require('./watcher')
var regionBasePath = config.regionPath || __dirname+'/world'
var staticBasePath = Path.join(__dirname, 'public')
var watcher = new Watcher(regionBasePath)
// watcher.start()
var staticRx = /\.(js|html|png|json)/i
var regionRx = /^\/regions\/(-?\d+)\/(-?\d+)$/i
var regionImgRx = /^\/cache\/(r\.-?\d+\.-?\d+-\w+\.png)$/i
var server = http.createServer(function(req, res) {
if (regionImgRx.test(req.url)) {
return serveRegionImg(req, res)
}
if (regionRx.test(req.url)) {
return serveRegion(req, res)
}
if (req.url == '/regions') {
return serveRegionList(req, res)
}
if (req.url == '/info') {
return serveInfo(req, res)
}
if (staticRx.test(req.url) || req.url === '/') {
return serveStatic(req, res)
}
res.write(req.url)
res.end()
})
server.listen(8000, function() {
console.log('Listening on http://localhost:8000/')
})
function serveRegionList(req, res) {
regionList(regionBasePath, function(err, regions) {
res.write(JSON.stringify(regions))
res.end()
})
}
function serveRegionImg(req, res) {
var matches = req.url.match(regionImgRx)
var img = matches[1]
var path = Path.join(__dirname, 'cache', img)
fs.createReadStream(path).pipe(res)
res.setHeader('content-type', 'image/png')
}
function serveRegion(req, res) {
var matches = req.url.match(regionRx)
var x = matches[1]
var z = matches[2]
var path = Path.join(__dirname, 'cache', 'r.'+x+'.'+z+'.json.gz')
fs.createReadStream(path).pipe(res)
res.setHeader('content-encoding', 'gzip')
res.setHeader('content-type', 'application/json')
}
function serveStatic(req, res) {
var path = req.url.replace(/\//g, '')
if (path == '') path = 'index.html'
fs.createReadStream(Path.join(staticBasePath, path)).pipe(res)
}
function serveInfo(req, res) {
var info = require('./blocks')
res.write(JSON.stringify({
blocks: info.blocks,
biomes: info.biomes
}))
res.end()
}