Explorar el Código

add save and load api calls.

Lucas Stadler %!s(int64=12) %!d(string=hace) años
padre
commit
d50abe128d
Se han modificado 2 ficheros con 31 adiciones y 0 borrados
  1. 1 0
      js/pixl/data/.gitignore
  2. 30 0
      js/pixl/server.js

+ 1 - 0
js/pixl/data/.gitignore

@ -0,0 +1 @@
1
*.json

+ 30 - 0
js/pixl/server.js

@ -1,6 +1,8 @@
1 1
var ws = require('ws');
2 2
var http = require('http');
3 3
var express = require('express');
4
var fs = require('fs');
5
var path = require('path');
4 6
5 7
var app = express();
6 8
app.use(express.static(__dirname + "/public"));
@ -28,6 +30,34 @@ app.get('/reset', function(req, res) {
28 30
	res.send(JSON.stringify({status: "ok"}));
29 31
});
30 32
33
app.get('/save/:name', function(req, res) {
34
	fs.writeFile(path.join('./data/', req.params.name + '.json'), JSON.stringify(world), function(err) {
35
		res.setHeader('Content-Type', 'text/plain');
36
		if (err) {
37
			res.statusCode = 404;
38
			res.send(JSON.stringify({error: err}));
39
		} else {
40
			res.send(JSON.stringify({name: req.params.name}));
41
		}
42
	});
43
});
44
45
app.get('/load/:name', function(req, res) {
46
	fs.readFile(path.join('./data', req.params.name + '.json'), function(err, data) {
47
		res.setHeader('Content-Type', 'text/plain');
48
		if (err) {
49
			res.statusCode = 404;
50
			res.send(JSON.stringify({error: err}));
51
		} else {
52
			world = JSON.parse(data);
53
			wss.clients.forEach(function(client) {
54
				client.send(JSON.stringify(world));
55
			});
56
			res.send(JSON.stringify({pixls: Object.keys(world).length}));
57
		}
58
	})
59
});
60
31 61
var server = http.createServer(app);
32 62
server.listen(8001);
33 63