-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
53 lines (46 loc) · 1.35 KB
/
app.js
File metadata and controls
53 lines (46 loc) · 1.35 KB
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
var http = require('http');
var router = require('http-router');
var routes = new router();
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var qs = require('querystring');
routes
.post('/', function(req, res, next) {
var data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
var type = req.headers['content-type'];
if (/application\/x-www-form-urlencoded/.test(type)) {
data = JSON.stringify(qs.parse(data));
}
emitter.emit('data', data);
res.writeHead(200, { 'Access-Control-Allow-Origin': '*' });
res.end();
});
})
.get('/', function(req, res, next) {
if (req.headers['accept'] !== 'text/event-stream') return res.end('');
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
var timer = setInterval(function() {
res.write(':\n\n');
}, 5000);
emitter.on('data', function(data) {
res.write('data: ' + data + '\n\n');
});
req.on('close', function() {
clearTimeout(timer);
});
});
http.createServer(function(req, res) {
if (!routes.route(req, res)) {
res.writeHead(500);
res.end('Error');
}
}).listen(process.env.PORT || 8080);