forked from NativeScript/nativescript-background-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (76 loc) · 2.56 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
var http = require("http");
var fs = require("fs");
function start(port, logger) {
var outDir = __dirname + "/uploads/";
var server = http.createServer(function(request, response) {
try {
var Throttle = require("stream-throttle").Throttle;
var fileName = request.headers["file-name"];
if (logger) {
logger.log(request.method + "Request! Content-Length: " + request.headers["content-length"] + ", file-name: " + fileName);
logger.dir(request.headers);
}
var out = outDir + "upload-" + new Date().getTime() + "-" + fileName;
if (logger) {
logger.log("Output in: " + out);
}
var total = request.headers["content-length"];
var current = 0;
var shouldFail = request.headers["should-fail"];
request.pipe(new Throttle({ rate: 1024 * 2048 })).pipe(fs.createWriteStream(out, { flags: 'w', encoding: null, fd: null, mode: 0666 }));
request.on('data', function(chunk) {
current += chunk.length;
if (shouldFail && (current / total > 0.25)) {
if (logger) {
logger.log("Error ");
}
var body = "Denied!";
response.writeHead(408, "Die!", { "Content-Type": "text/plain", "Content-Length": body.length, "Connection": "close" });
response.write(body);
response.end();
shouldFail = false;
if (logger) {
logger.log("Terminated with error: [" + out + "]: " + current + " / " + total + " " + Math.floor(100 * current / total) + "%");
}
} else {
if (logger) {
logger.log("Data [" + out + "]: " + current + " / " + total + " " + Math.floor(100 * current / total) + "%");
}
}
});
request.on('end', function () {
setTimeout(function() {
if (logger) {
logger.log("Done (" + out + ")");
}
var body = "Upload complete!";
response.writeHead(200, "Done!", { "Content-Type": "text/plain", "Content-Length": body.length });
response.write(body);
response.end();
}, 10000);
});
if (logger) {
request.on('error', function(e) {
logger.log('error!');
logger.log(e);
});
}
} catch(e) {
if (logger) {
logger.log(e);
}
throw e;
}
});
server.listen(port);
if (logger) {
logger.log("Server is listening on: " + port);
logger.log("Uploads are saved to: " + outDir);
}
return {
close: function() {
server.close();
}
}
}
exports.start = start;