-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
61 lines (57 loc) · 1.53 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
var sys = require('sys');
var http = require('http');
var static = require('node-static');
var fs = require('fs');
var url = require('url');
var fileServer = new static.Server('.');
var img_folder = "img/";
var img_count = fs.readdirSync(img_folder).length;
console.log("Found "+img_count+" already saved image(s).");
http.createServer(function (req, res) {
if (req.method == "GET")
{
var pathname = url.parse(req.url, true).pathname;
if (pathname == "/index.html" || pathname == "/")
{
var data = fs.readFileSync("index.html", "utf-8");
data = data.replace(
/\/\*server data from\*\/[\d\D]*\/\*server data to\*\//,
"\""+img_folder+(img_count-1)+".png\"");
req.addListener('end', function () {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
return;
}
}
else
if (req.method == "POST")
{
var data = "";
req.addListener('data', function (chunk) {
data += chunk;
}).addListener('end', function () {
try {
fs.writeFile(img_folder+(img_count++)+".png",
data.substr(22), "base64",
function (err) {
if (err) throw err;
console.log(img_count+" image(s) saved.");
});
} catch(e) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.write(e.toString());
res.end();
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Done!');
res.end();
});
return;
}
req.addListener('end', function () {
fileServer.serve(req, res);
});
}).listen(9004);
console.log("Server started.")