-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathserver.js
More file actions
54 lines (44 loc) · 1.34 KB
/
server.js
File metadata and controls
54 lines (44 loc) · 1.34 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
54
// https://github.com/szym/display
// Copyright (c) 2014, Szymon Jakubczak (MIT License)
var http = require('http')
, express = require('express')
, getRawBody = require('raw-body');
// Forwards any data POSTed to /events to an event-stream at /events.
// Serves files from /static otherwise.
function createServer() {
var app = express();
app.get('/events', function(req, res) {
// Max timeout that fits in signed int32.
var TIMEOUT_MAX = 0x7FFFFFFF; // 2^31-1
req.socket.setTimeout(TIMEOUT_MAX);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write('\n\n');
function forwardEvent(data) {
res.write('data: ');
res.write(data);
res.write('\n\n');
}
// exploit the fact that app is an EventEmitter
app.on('update', forwardEvent);
req.once('close', function() {
app.removeListener('update', forwardEvent);
});
});
app.post('/events', function(req, res, next) {
getRawBody(req, {
length: req.headers['content-length'],
limit: '20mb',
}, function(err, body) {
if (err) return next(err);
app.emit('update', body);
res.status(200).end();
});
});
app.use(express.static(__dirname + '/static'));
return app;
};
module.exports = createServer;