-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (75 loc) · 1.93 KB
/
index.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
var DemoParser = require('@demostf/demo.js');
var express = require('express');
var app = express();
var url = require('url');
var https = require('https');
var http = require('http');
app.set('port', (process.env.PORT || 80));
app.use(express.static(__dirname + '/public'));
app.get('/', function (request, response) {
response.send('Hello World!');
});
function handleDataStream (stream, cb, slow) {
var buffers = [];
stream.on('data', function (buffer) {
buffers.push(buffer);
});
stream.on('end', function () {
try {
var buffer = Buffer.concat(buffers);
var demo = DemoParser.Demo.fromNodeBuffer(buffer);
var parser = demo.getAnalyser(!slow);
var header = parser.getHeader();
var match = parser.getBody();
var body = match.getState();
body.header = header;
cb(body);
} catch (e) {
cb(e);
}
});
}
app.post('/parse/slow', function (req, res) {
handleDataStream(req, function (body) {
res.set('Content-Type', 'application/json');
res.write(JSON.stringify(body));
res.end();
}, true)
});
app.post('/parse', function (req, res) {
handleDataStream(req, function (body) {
res.set('Content-Type', 'application/json');
res.write(JSON.stringify(body));
res.end();
}, false)
});
app.post('/url', function (req, res) {
var reqUrl = '';
req.on('data', function (buffer) {
reqUrl += buffer;
});
req.on('end', function () {
var options = url.parse(reqUrl);
if (options.protocol === 'https:') {
var handler = https;
} else {
handler = http;
}
handler.request(options, function (response) {
handleDataStream(response, function (body) {
res.set('Content-Type', 'application/json');
res.write(JSON.stringify(body));
res.end();
})
}).end();
});
});
app.listen(app.get('port'), function () {
console.log("Node app is running at localhost:" + app.get('port'));
});
process.on('SIGINT', function () {
process.exit();
});
process.on('SIGTERM', function () {
process.exit();
});